Example usage for java.net SocketTimeoutException getMessage

List of usage examples for java.net SocketTimeoutException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.jute.fed4j.engine.component.http.HttpDispatcherImpl_Jakarta.java

public void run(HttpComponent component) {
    this.commponent = component;
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, component.connectTimeout);
    HttpConnectionParams.setSoTimeout(params, component.readTimeout);

    try {//from  w  w  w  . ja va 2s  .  c  o  m
        this.init(component);
        HttpClient httpclient = new MyHttpClient(
                getConnectionManager(params, component.enablePersistentConnection), params);
        if (component.enableProxy && "http".equals(component.proxyType)) {
            HttpHost proxy = new HttpHost(component.proxyHost, component.proxyPort, component.proxyType);
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        HttpUriRequest request = new HttpRequest(component.method, component.uri);
        MyHttpResponseHandler responseHandler = new MyHttpResponseHandler(component.responseCharset);
        String body = httpclient.execute(request, responseHandler);
        this.onResponse(component, responseHandler.code, body);
    } catch (SocketTimeoutException e) {
        onException(component, -2, " socket timeout error occurs: " + e.getMessage());
    } catch (ClientProtocolException e) {
        onException(component, -3, " error resposed from server: " + e.getMessage());
    } catch (IOException e) {
        onException(component, -4, " error occurs during dispatch: " + e.getMessage());
    } catch (Exception e) {
        onException(component, -5, "error occurs during parsing xml:" + e.getMessage());
    }
}

From source file:com.mirth.connect.connectors.tcp.protocols.DefaultProtocol.java

public byte[] read(InputStream is) throws IOException {
    String charset = _tcpConnector.getCharsetEncoding();
    UtilReader myReader = new UtilReader(is, charset);

    int c = 0;//from  w  w  w  .j  a  va  2 s.c  o  m
    try {
        c = myReader.read();
    } catch (SocketException e) {
        logger.info(
                "SocketException on read() attempt.  Socket appears to have been closed: " + e.getMessage());
        // Throw the exception so the socket can always be recycled.
        throw e;
    } catch (SocketTimeoutException ste) {
        logger.info("SocketTimeoutException on read() attempt.  Socket appears to have been closed: "
                + ste.getMessage());
        /*
         * Throw the exception so the listener can know it was a timeout and
         * decide whether or not to recycle the connection.
         */
        throw ste;
    }

    // trying to read when there is no data (stream may have been closed at
    // other end)
    if (c == -1) {
        logger.info("End of input stream reached.");
        return null;
    }

    while (c != -1) {
        myReader.append((char) c);
        try {
            c = myReader.read();
        } catch (Exception e) {
            c = -1;
        }
    }

    return myReader.getBytes();
}

From source file:org.apache.hadoop.net.TestSocketIOWithTimeout.java

private void doIO(InputStream in, OutputStream out) throws IOException {
    /* Keep on writing or reading until we get SocketTimeoutException.
     * It expects this exception to occur within 100 millis of TIMEOUT.
     *///  ww  w  .  j  a  v  a  2s .  c  om
    byte buf[] = new byte[4192];

    while (true) {
        long start = System.currentTimeMillis();
        try {
            if (in != null) {
                in.read(buf);
            } else {
                out.write(buf);
            }
        } catch (SocketTimeoutException e) {
            long diff = System.currentTimeMillis() - start;
            LOG.info("Got SocketTimeoutException as expected after " + diff + " millis : " + e.getMessage());
            assertTrue(Math.abs(TIMEOUT - diff) <= 200);
            break;
        }
    }
}

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./*  w ww  .j  a v a  2 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:org.archive.modules.fetcher.HeritrixProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//from   w  ww.  jav a2 s  . co  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();

        InetAddress hostAddress;
        Thread current = Thread.currentThread();
        if (current instanceof HostResolver) {
            HostResolver resolver = (HostResolver) current;
            hostAddress = resolver.resolve(host);
        } else {
            hostAddress = 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.amazonaws.mobileconnectors.s3.transferutility.DownloadTask.java

/**
 * Writes stream data into a file.//  w  ww.  j a v a  2 s .co  m
 *
 * @param is input stream
 * @param file file to be written
 */
private void saveToFile(InputStream is, File file) {
    // attempt to create the parent if it doesn't exist
    final File parentDirectory = file.getParentFile();
    if (parentDirectory != null && !parentDirectory.exists()) {
        parentDirectory.mkdirs();
    }

    final boolean append = file.length() > 0;
    OutputStream os = null;
    try {
        os = new BufferedOutputStream(new FileOutputStream(file, append));
        final byte[] buffer = new byte[SIXTEEN_KB];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
    } catch (final SocketTimeoutException socketTimeoutException) {
        String errorString = "SocketTimeoutException: Unable to retrieve contents over network: "
                + socketTimeoutException.getMessage();
        LOGGER.error(errorString);
        throw new AmazonClientException(errorString, socketTimeoutException);
    } catch (final IOException e) {
        throw new AmazonClientException("Unable to store object contents to disk: " + e.getMessage(), e);
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (final IOException ioe) {
            LOGGER.warn("got exception", ioe);
        }
        try {
            is.close();
        } catch (final IOException ioe) {
            LOGGER.warn("got exception", ioe);
        }
    }
}

From source file:com.cloud.baremetal.networkservice.SecurityGroupHttpClient.java

public HashMap<String, Pair<Long, Long>> sync(String vmName, Long vmId, String agentIp) {
    HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>();
    PostMethod post = new PostMethod(String.format("http://%s:%s/", agentIp, getPort()));
    try {// ww w  .  java  2  s.  c o m
        post.addRequestHeader("command", "sync");
        if (httpClient.executeMethod(post) != 200) {
            logger.debug(String.format("echoing baremetal security group agent on %s got error: %s", agentIp,
                    post.getResponseBodyAsString()));
        } else {
            String res = post.getResponseBodyAsString();
            // res = ';'.join([vmName, vmId, seqno])
            String[] rulelogs = res.split(",");
            if (rulelogs.length != 6) {
                logger.debug(
                        String.format("host[%s] returns invalid security group sync document[%s], reset rules",
                                agentIp, res));
                states.put(vmName, new Pair<Long, Long>(vmId, -1L));
                return states;
            }
            Pair<Long, Long> p = new Pair<Long, Long>(Long.valueOf(rulelogs[1]), Long.valueOf(rulelogs[5]));
            states.put(rulelogs[0], p);
            return states;
        }
    } catch (SocketTimeoutException se) {
        logger.warn(
                String.format("unable to sync security group rules on host[%s], %s", agentIp, se.getMessage()));
    } catch (Exception e) {
        logger.warn(String.format("unable to sync security group rules on host[%s]", agentIp), e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
    return states;
}

From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java

/**
 * Performs the web site monitoring by checking the response code of the site's URL.
 * /*from   w  w w  .ja v a  2  s  . com*/
 * @param build
 *            the build
 * @param launcher
 *            the launcher
 * @param listener
 *            the listener
 * @return true if all sites give success response codes, false otherwise
 * @throws InterruptedException
 *             when there's an interruption
 * @throws IOException
 *             when there's an IO error
 */
@Override
public final boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher,
        final BuildListener listener) throws InterruptedException, IOException {
    List<Result> results = new ArrayList<Result>();
    SiteMonitorDescriptor descriptor = (SiteMonitorDescriptor) getDescriptor();

    if (CookieHandler.getDefault() == null) {
        CookieHandler.setDefault(new CookieManager());
    }

    boolean hasFailure = false;
    for (Site site : mSites) {

        Integer responseCode = null;
        Status status;
        String note = "";
        HttpURLConnection connection = null;

        try {
            connection = getConnection(site.getUrl());

            if (site.getTimeout() != null) {
                connection.setConnectTimeout(site.getTimeout() * MILLISECS_IN_SECS);
            } else {
                connection.setConnectTimeout(descriptor.getTimeout() * MILLISECS_IN_SECS);
            }

            responseCode = connection.getResponseCode();

            List<Integer> successResponseCodes = descriptor.getSuccessResponseCodes();

            if (site.getSuccessResponseCodes() != null && site.getSuccessResponseCodes().size() > 0) {
                successResponseCodes = site.getSuccessResponseCodes();
            }

            if (successResponseCodes.contains(responseCode)) {
                status = Status.UP;
            } else {
                status = Status.ERROR;
            }
        } catch (SocketTimeoutException ste) {
            listener.getLogger().println(ste + " - " + ste.getMessage());
            status = Status.DOWN;
        } catch (Exception e) {
            note = e + " - " + e.getMessage();
            listener.getLogger().println(note);
            status = Status.EXCEPTION;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        note = "[" + status + "] " + note;
        listener.getLogger()
                .println(Messages.SiteMonitor_Console_URL() + site.getUrl() + ", "
                        + Messages.SiteMonitor_Console_ResponseCode() + responseCode + ", "
                        + Messages.SiteMonitor_Console_Status() + status);

        if (!hasFailure && status != Status.UP) {
            hasFailure = true;
        }

        Result result = new Result(site, responseCode, status, note);
        results.add(result);
    }

    build.addAction(new SiteMonitorRootAction(results));
    hudson.model.Result result;
    if (hasFailure) {
        result = hudson.model.Result.FAILURE;
    } else {
        result = hudson.model.Result.SUCCESS;
    }
    build.setResult(result);

    // the return value is not used when this class implements a Recorder,
    // it's left here just in case this class switches to a Builder.
    // http://n4.nabble.com/how-can-a-Recorder-mark-build-as-failure-td1746654.html
    return !hasFailure;
}

From source file:prototypes.ws.proxy.soap.proxy.ProxyServlet.java

/**
 * Recept all request.// ww  w  . j  a  va2s .  c o  m
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpURLConnection httpConn = null;
    LOGGER.debug("doRequest");
    BackendExchange backendExchange = RequestContext.getBackendExchange(request);
    LOGGER.trace("BackendExchange Hashcode : {}", Integer.toHexString(backendExchange.hashCode()));
    try {
        URL targetUrl = Requests.resolveTargetUrl(request, backendExchange.getUri());
        httpConn = prepareBackendConnection(targetUrl, request, backendExchange.getRequestHeaders());

        // save final state of request headers
        backendExchange.setRequestHeaders(httpConn.getRequestProperties());

        // Send request
        byte[] body = backendExchange.getRequestBody();

        backendExchange.start();
        boolean gzipped = false;
        try {
            if (body.length > 0) {
                httpConn.getOutputStream().write(body);
            } else {
                LOGGER.warn("Body Empty");
            }

            gzipped = "gzip".equals(httpConn.getContentEncoding());
            // Get response. If response is gzipped, uncompress it

            backendExchange.setResponseBody(Streams.getBytes(httpConn.getInputStream(), gzipped));
        } catch (java.net.SocketTimeoutException ex) {
            throw new IOException("Time out : " + ex.getMessage(), ex);
        } catch (IOException ex) {
            LOGGER.warn("Failed to read target response body {}", ex);
            backendExchange.setResponseBody(Streams.getBytes(httpConn.getErrorStream(), gzipped));
        } finally {
            backendExchange.stop();
        }

        // Stores infos
        backendExchange.setResponseCode(httpConn.getResponseCode());
        backendExchange.setResponseHeaders(httpConn.getHeaderFields());

        // Specific error code treatment
        switch (backendExchange.getResponseCode()) {
        case 0:
            // No response
            LOGGER.debug("ResponseCode =  0 !!!");
            Requests.sendErrorServer(request, response,
                    String.format(ProxyErrorConstants.EMPTY_RESPONSE, targetUrl.toString()));
            return;
        case 404:
            LOGGER.debug("404 returned");
            Requests.sendErrorServer(request, response,
                    String.format(ProxyErrorConstants.NOT_FOUND, targetUrl.toString()), 404);
            return;
        default:
            break;
        }

        // return response with filtered headers
        List<String> respHeadersToIgnore = new ArrayList<String>(RESP_HEADERS_TO_IGNORE);
        addResponseHeaders(response, backendExchange, respHeadersToIgnore);
        response.setStatus(backendExchange.getResponseCode());

        response.getOutputStream().write(backendExchange.getResponseBody());
    } catch (IllegalStateException e1) {
        // bad url
        Requests.sendErrorClient(request, response, e1.getMessage());
    } catch (ClassCastException ex) {
        // bad url
        Requests.sendErrorClient(request, response, ex.getMessage());
    } catch (IOException ex) {
        LOGGER.error("Backend call in ERROR");
        // bad call
        Requests.sendErrorServer(request, response, ex.getMessage());
    } catch (Exception ex) {
        LOGGER.error("Error during proxying : {}", ex);
        // protect from all exceptions
        Requests.sendInternalErrorServer(request, response, ex.getMessage());
    } finally {
        LOGGER.trace("BackendExchange Hashcode : {}", Integer.toHexString(backendExchange.hashCode()));
        LOGGER.debug("BackendExchange : {}", backendExchange);
        if (httpConn != null) {
            try {
                httpConn.disconnect();
            } catch (Exception ex) {
                LOGGER.warn("Error on disconnect {}", ex);
            }
        }
    }
}