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(String msg) 

Source Link

Document

Constructs a new SocketTimeoutException with a detail message.

Usage

From source file:com.buaa.cfs.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 *
 * @param channel  - this should be a {@link SelectableChannel}
 * @param endpoint//from   w  w  w .ja  v a2s.  com
 *
 * @throws IOException
 * @see SocketChannel#connect(SocketAddress)
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (Time.now() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}

From source file:eu.stratosphere.nephele.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.
 * /*from w ww. jav  a2 s  . c om*/
 * @param buf
 *        buffer for IO
 * @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.
}

From source file:com.proofpoint.http.client.ApacheHttpClient.java

public <T, E extends Exception> T execute(Request request, final ResponseHandler<T, E> responseHandler)
        throws E {
    Preconditions.checkNotNull(request, "request is null");
    Preconditions.checkNotNull(responseHandler, "responseHandler is null");

    for (HttpRequestFilter requestFilter : requestFilters) {
        request = requestFilter.filterRequest(request);
    }//from  ww  w  .  j  a v  a 2  s . c  o  m

    final long requestStart = System.nanoTime();
    final StatsHttpUriRequest httpUriRequest = StatsHttpUriRequest.createGenericHttpRequest(request);
    final Request finalRequest = request;
    try {
        T value = httpClient.execute(httpUriRequest, new org.apache.http.client.ResponseHandler<T>() {
            @Override
            public T handleResponse(HttpResponse httpResponse) throws IOException {
                long responseStart = System.nanoTime();

                Response response = new MyResponse(httpResponse);
                try {
                    T value = responseHandler.handle(finalRequest, response);
                    return value;
                } catch (Exception e) {
                    throw new ExceptionFromResponseHandler(e);
                } finally {
                    Duration responseProcessingTime = Duration.nanosSince(responseStart);
                    Duration requestProcessingTime = new Duration(responseStart - requestStart,
                            TimeUnit.NANOSECONDS);

                    stats.record(finalRequest.getMethod(), response.getStatusCode(),
                            httpUriRequest.getBytesWritten(), response.getBytesRead(), requestProcessingTime,
                            responseProcessingTime);
                }
            }
        });
        return value;
    } catch (Exception e) {
        if (e instanceof ExceptionFromResponseHandler) {
            try {
                throw (E) e.getCause();
            } catch (ClassCastException classCastException) {
                // this should never happen but generics suck so be safe
                // handler will be notified of the same exception again below
            }
        } else if (e instanceof ConnectTimeoutException) {
            // apache http client eats the socket timeout exception
            SocketTimeoutException socketTimeoutException = new SocketTimeoutException(e.getMessage());
            socketTimeoutException.setStackTrace(e.getStackTrace());
            return responseHandler.handleException(request, socketTimeoutException);
        }
        return responseHandler.handleException(request, e);
    }
}

From source file:eu.stratosphere.nephele.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 * //from   w  ww.  j a  va 2s.com
 * @see SocketChannel#connect(SocketAddress)
 * @param channel
 *        - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}

From source file:com.apporiented.hermesftp.parser.impl.FtpCmdReaderThread.java

/**
 * {@inheritDoc}//from   ww w  .j av a 2  s .c o  m
 */
public FtpCmd waitForNextCommand(int timeout) throws FtpIllegalCmdException, SocketTimeoutException {
    FtpCmd cmd;
    synchronized (cmdLock) {
        long startStamp = System.currentTimeMillis();
        while (!cmdAvailable() && !errAvailable()) {
            try {
                cmdLock.wait(timeout);
            } catch (InterruptedException e) {
                log.debug("Thread " + this.getName() + " has been interrupted.");
            }
            if (startStamp + timeout < System.currentTimeMillis()) {
                throw new SocketTimeoutException("Command reader timeout.");
            }
            if (isTerminated()) {
                break;
            }
        }
        String err = consumeNextError();
        if (err != null) {
            throw new FtpIllegalCmdException(err);
        }

        cmd = consumeNextCommand();
        lastCmd = cmd;
        cmdLock.notifyAll();
    }
    return cmd;
}

From source file:com.mirth.connect.connectors.tests.StreamHandlerTests.java

@Test
public void readSingleMessage() throws Exception {
    byte[] testBytes = testMessageBytes;
    BatchStreamReader batchStreamHandler;
    StreamHandler streamHandler;/*from   w  ww  . j a v a  2 s.com*/
    ByteArrayOutputStream bos;
    InputStream is;
    int maxRead;

    // Create regular LLP frame with HL7 message
    bos = new ByteArrayOutputStream();
    bos.write(llpStartBytes);
    bos.write(testBytes);
    bos.write(llpEndBytes);
    // Create an input stream from the bytes
    is = new ByteArrayInputStream(bos.toByteArray());
    batchStreamHandler = new DefaultBatchStreamReader(is);
    streamHandler = new FrameStreamHandler(is, null, batchStreamHandler, defaultMLLPProps);
    // Assert that the bytes returned from the stream handler are correct
    assertTrue(Arrays.equals(testBytes, streamHandler.read()));

    // Create LLP frame with extra bytes at the beginning
    bos = new ByteArrayOutputStream();
    bos.write("Testing".getBytes(testMessageCharset));
    bos.write(llpStartBytes);
    bos.write(testBytes);
    bos.write(llpEndBytes);
    // Create an input stream from the bytes
    is = new ByteArrayInputStream(bos.toByteArray());
    batchStreamHandler = new DefaultBatchStreamReader(is);
    streamHandler = new FrameStreamHandler(is, null, batchStreamHandler, defaultMLLPProps);
    // Assert that the bytes returned from the stream handler are correct
    assertTrue(Arrays.equals(testBytes, streamHandler.read()));

    // Create LLP frame with extra bytes at the end
    bos = new ByteArrayOutputStream();
    bos.write(llpStartBytes);
    bos.write(testBytes);
    bos.write(llpEndBytes);
    bos.write("Testing".getBytes(testMessageCharset));
    // Create an input stream from the bytes
    is = new ByteArrayInputStream(bos.toByteArray());
    batchStreamHandler = new DefaultBatchStreamReader(is);
    streamHandler = new FrameStreamHandler(is, null, batchStreamHandler, defaultMLLPProps);
    // Assert that the bytes returned from the stream handler are correct
    assertTrue(Arrays.equals(testBytes, streamHandler.read()));

    // Create LLP frame with extra bytes at the beginning and end
    bos = new ByteArrayOutputStream();
    bos.write("Testing".getBytes(testMessageCharset));
    bos.write(llpStartBytes);
    bos.write(testBytes);
    bos.write(llpEndBytes);
    bos.write("Testing".getBytes(testMessageCharset));
    // Create an input stream from the bytes
    is = new ByteArrayInputStream(bos.toByteArray());
    batchStreamHandler = new DefaultBatchStreamReader(is);
    streamHandler = new FrameStreamHandler(is, null, batchStreamHandler, defaultMLLPProps);
    // Assert that the bytes returned from the stream handler are correct
    assertTrue(Arrays.equals(testBytes, streamHandler.read()));

    class FailingByteArrayInputStream extends ByteArrayInputStream {
        private int maxRead;
        private int numRead;

        public FailingByteArrayInputStream(byte[] buf, int maxRead) {
            super(buf);
            this.maxRead = maxRead;
            numRead = 0;
        }

        @Override
        public int read() {
            if (++numRead > maxRead) {
                throw new RuntimeException("fail");
            }
            return super.read();
        }
    }

    // Create regular LLP frame
    bos = new ByteArrayOutputStream();
    bos.write(llpStartBytes);
    bos.write(testBytes);
    bos.write(llpEndBytes);
    // Create an input stream that will throw an exception
    maxRead = 50;
    is = new FailingByteArrayInputStream(bos.toByteArray(), maxRead);
    // Allow the stream handler to return data when an exception occurs
    batchStreamHandler = new DefaultBatchStreamReader(is);
    streamHandler = new FrameStreamHandler(is, null, batchStreamHandler, defaultMLLPProps);
    ((FrameStreamHandler) streamHandler).setReturnDataOnException(true);
    // Assert that the bytes returned from the stream handler are correct
    assertTrue(Arrays.equals(Arrays.copyOf(testBytes, maxRead - llpStartBytes.length), streamHandler.read()));

    class FailingFilterInputStream extends FilterInputStream {
        private int maxRead;
        private int numRead;
        private boolean fail = true;

        public FailingFilterInputStream(InputStream in, int maxRead) {
            super(in);
            this.maxRead = maxRead;
            numRead = 0;
        }

        public void toggleFail() {
            fail = !fail;
        }

        @Override
        public int read() throws IOException {
            if (numRead >= maxRead && fail) {
                throw new SocketTimeoutException("fail");
            }
            int result = super.read();
            numRead++;
            return result;
        }
    }

    // Create regular LLP frame
    bos = new ByteArrayOutputStream();
    bos.write(llpStartBytes);
    bos.write(testBytes);
    bos.write(llpEndBytes);
    // Create an input stream that will throw an exception
    maxRead = 50;
    is = new FailingFilterInputStream(new ByteArrayInputStream(bos.toByteArray()), maxRead);
    // Allow the stream handler to return data when an exception occurs
    batchStreamHandler = new DefaultBatchStreamReader(is);
    streamHandler = new FrameStreamHandler(is, null, batchStreamHandler, defaultMLLPProps);
    ((FrameStreamHandler) streamHandler).setReturnDataOnException(true);
    // Assert that the bytes returned from the stream handler are correct
    assertTrue(Arrays.equals(Arrays.copyOf(testBytes, maxRead - llpStartBytes.length), streamHandler.read()));

    // Create regular LLP frame
    bos = new ByteArrayOutputStream();
    bos.write(llpStartBytes);
    bos.write(testBytes);
    bos.write(llpEndBytes);
    // Create an input stream that will throw an exception
    maxRead = 50;
    is = new FailingFilterInputStream(new ByteArrayInputStream(bos.toByteArray()), maxRead);
    // Allow the stream handler to return data when an exception occurs
    batchStreamHandler = new DefaultBatchStreamReader(is);
    streamHandler = new FrameStreamHandler(is, null, batchStreamHandler, defaultMLLPProps);
    ((FrameStreamHandler) streamHandler).setReturnDataOnException(true);
    // Get the first set of bytes
    byte[] firstBytes = streamHandler.read();
    // Turn failing off and get the rest of the bytes
    ((FailingFilterInputStream) is).toggleFail();
    byte[] nextBytes = streamHandler.read();
    // Assert that the concatenation of both byte arrays is equivalent to the original message
    assertTrue(Arrays.equals(testBytes, ArrayUtils.addAll(firstBytes, nextBytes)));
}

From source file:com.buaa.cfs.net.SocketIOWithTimeout.java

/**
 * This is similar to {@link #doIO(ByteBuffer, int)} except that it does not perform any I/O. It just waits for the
 * channel to be ready for I/O as specified in ops.
 *
 * @param ops Selection Ops used for waiting
 *
 * @throws SocketTimeoutException if select on the channel times out.
 * @throws IOException            if any other I/O error occurs.
 *//*from  ww w. j  ava 2 s  .  com*/
void waitForIO(int ops) throws IOException {

    if (selector.select(channel, ops, timeout) == 0) {
        throw new SocketTimeoutException(timeoutExceptionString(channel, timeout, ops));
    }
}

From source file:windows.webservices.utilidades.EjecutorJson.java

private <T> T ejecutarJsonGeneral(Request request, Class<? extends List> colleccion, Class<? extends Map> map,
        Class<?> key, Class<T> mappe) throws IOException {

    try {// ww w .j a v a  2s.  c  o m
        System.out.println("enlace : " + request.urlString()
                + (json != null && !json.isEmpty() ? "\n body :" + json : ""));
        Response response = client.newCall(request).execute();

        ultimoJson = response.body().string();
        if (colleccion != null) {
            return (T) mapperToList(ultimoJson, mappe);
        } else if (map != null) {
            return (T) mapperToMap(ultimoJson, map, key, mappe);
        } else {
            if (mappe.equals(String.class)) {
                return (T) ultimoJson;
            }
            return mapper.readValue(ultimoJson, mappe);
        }
    } catch (IOException ex) {
        if ((ex instanceof JsonParseException) || (ex instanceof EOFException)) {

            if ((ultimoJson.contains(EXCEPTION_REPORT)
                    || ultimoJson.contains(ERROR_REPORT) | ultimoJson.contains(INFORME_ERROR))
                    && ultimoJson.contains(MESSAGE) && ultimoJson.contains(DESCRIPTION)) {
                String title = ultimoJson.substring(ultimoJson.indexOf("<h1>") + 4,
                        ultimoJson.indexOf("</h1>"));
                String[] tags = ultimoJson.split("<p>");
                String msj = tags[2].substring(tags[2].indexOf("<u>") + 3, tags[2].indexOf("</u>"));
                String desb = tags[3].substring(tags[3].indexOf("<u>") + 3, tags[3].indexOf("</u>"));

                Logger.getLogger(EjecutorJson.class.getName()).log(Level.INFO,
                        "Titulo : {0}\nMensaje : {1}\nDescripcin : {2}", new String[] { title, msj, desb });
                throw new RuntimeException();
            }
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.WARNING,
                    "No se pudo castear el siguiente jSon : \n {0}", ultimoJson);

        } else if (ex instanceof SocketTimeoutException) {
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.WARNING,
                    "Se agoto el tiempo de respuesta");

            throw new SocketTimeoutException("Se agoto el tiempo de respuesta");
        } else if (ex instanceof ConnectException) {
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.WARNING,
                    "No se pudo conectar al servidor");
            throw new ConnectException("No se pudo conectar al servidor");

        } else {
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

From source file:com.hoccer.tools.HttpHelper.java

private static HttpResponse executeHTTPMethod(HttpRequestBase pMethod, int pConnectionTimeout)
        throws IOException, HttpClientException, HttpServerException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, pConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, pConnectionTimeout);
    HttpClientParams.setRedirecting(httpParams, true);

    DefaultHttpClient httpclient = new HttpClientWithKeystore(httpParams);

    // Log redirects
    httpclient.setRedirectHandler(new DefaultRedirectHandler() {
        @Override//from  w  ww  .j  a  v  a 2  s . c  o  m
        public URI getLocationURI(HttpResponse response, HttpContext context) throws ProtocolException {
            URI uri = super.getLocationURI(response, context);
            return uri;
        }
    });

    HttpResponse response;
    try {
        response = httpclient.execute(pMethod);
    } catch (SocketTimeoutException e) {
        e = new SocketTimeoutException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    } catch (SocketException e) {
        e = new SocketException(e.getMessage() + ": " + pMethod.getURI());
        e.fillInStackTrace();
        throw e;
    }
    HttpException.throwIfError(pMethod.getURI().toString(), response);
    return response;
}