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.mirth.connect.connectors.mllp.protocols.LlpProtocol.java

private byte[] readTCP(InputStream is) throws IOException {
    String charset = _mllpConnector.getCharsetEncoding();
    UtilReader myReader = new UtilReader(is, charset);

    int c = 0;/*from w w  w  .j a  v a2 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());
        return null;
    } catch (SocketTimeoutException ste) {
        logger.info("SocketTimeoutException on read() attempt.  Socket appears to have been closed: "
                + ste.getMessage());
        return null;
    }

    // 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:microsoft.aspnet.signalr.client.http.android.AndroidHttpConnection.java

@Override
public HttpConnectionFuture execute(final Request request, final ResponseCallback responseCallback) {

    mLogger.log("Create new AsyncTask for HTTP Connection", LogLevel.Verbose);

    final HttpConnectionFuture future = new HttpConnectionFuture();

    final RequestTask requestTask = new RequestTask() {

        AndroidHttpClient mClient;/*from   www .ja va 2 s .  co  m*/
        InputStream mResponseStream;

        @Override
        protected Void doInBackground(Void... voids) {
            if (request == null) {
                future.triggerError(new IllegalArgumentException("request"));
            }

            mClient = AndroidHttpClient.newInstance(Platform.getUserAgent());
            mResponseStream = null;
            URI uri;

            try {
                mLogger.log("Create an Android-specific request", LogLevel.Verbose);
                request.log(mLogger);
                HttpRequest realRequest = createRealRequest(request);
                uri = new URI(request.getUrl());

                HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());

                mLogger.log("Execute the HTTP Request", LogLevel.Verbose);
                HttpResponse response;

                try {
                    response = mClient.execute(host, realRequest);
                } catch (SocketTimeoutException timeoutException) {
                    closeStreamAndClient();
                    mLogger.log("Timeout executing request: " + timeoutException.getMessage(),
                            LogLevel.Information);

                    future.triggerTimeout(timeoutException);

                    return null;
                }

                mLogger.log("Request executed", LogLevel.Verbose);

                mResponseStream = response.getEntity().getContent();
                Header[] headers = response.getAllHeaders();
                Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                for (Header header : headers) {
                    String headerName = header.getName();
                    if (headersMap.containsKey(headerName)) {
                        headersMap.get(headerName).add(header.getValue());
                    } else {
                        List<String> headerValues = new ArrayList<String>();
                        headerValues.add(header.getValue());
                        headersMap.put(headerName, headerValues);
                    }
                }

                responseCallback.onResponse(new StreamResponse(mResponseStream,
                        response.getStatusLine().getStatusCode(), headersMap));
                future.setResult(null);
                closeStreamAndClient();
            } catch (Exception e) {
                closeStreamAndClient();
                mLogger.log("Error executing request: " + e.getMessage(), LogLevel.Critical);

                future.triggerError(e);
            }

            return null;
        }

        protected void closeStreamAndClient() {
            if (mResponseStream != null) {
                try {
                    mResponseStream.close();
                } catch (IOException e) {
                }
            }

            if (mClient != null) {
                mClient.close();
            }
        }
    };

    future.onCancelled(new Runnable() {

        @Override
        public void run() {
            AsyncTask<Void, Void, Void> cancelTask = new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    requestTask.closeStreamAndClient();
                    return null;
                }
            };

            executeTask(cancelTask);
        }
    });

    executeTask(requestTask);

    return future;
}

From source file:org.hlc.http.resetfull.network.HttpExecutor.java

/**
 * Do execute./*from w  w w. j  a v a 2s. c o m*/
 *
 * @param <E> the element type
 * @param httpMethod the http method
 * @param readTimeout the read timeout
 * @param result the result
 * @return the e
 */
protected <E> E doExecute(HttpUriRequest httpMethod, int readTimeout, MessageResolve<E> result) {
    try {
        // Step1 ?
        HttpParams httpParams = buildHttpParams(readTimeout);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        httpMethod.setHeader("User-Agent", "");
        for (Entry<String, String> item : httpHeaderParamter.entrySet()) {
            httpMethod.setHeader(item.getKey(), item.getValue());
        }
        HttpContext context = new BasicHttpContext();

        // Step2 
        HttpResponse response = httpClient.execute(httpMethod, context);
        Header contentType = response.getFirstHeader("Content-Type");
        HeaderElement[] elements = contentType.getElements();
        int stausCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        String responseBody = EntityUtils.toString(entity);
        Log.info(stausCode + "/" + contentType.getValue() + "/" + responseBody);

        // Step3 ??
        Message errorMessage = this.messageFilter.resolve(stausCode, elements[0].getName(), responseBody);
        if (errorMessage == null) {
            throw new IllegalArgumentException("HTTP parsing results cannot be empty.");
        }
        if (errorMessage.getCode() != HttpStatus.SC_OK) {
            result.error(errorMessage.getCode(), errorMessage.getMessageType(), errorMessage.getMessage());
            return null;
        }
        return result.resolve(errorMessage.getMessageType(), errorMessage.getMessage());
    } catch (SocketTimeoutException e) {
        Log.debug(e.getMessage());
        result.error(NETWORK_ERROR, DEFUALT_MESSAGE_TYPE, e.getMessage());
        return null;
    } catch (Exception e) {
        Log.debug(e.getMessage());
        result.error(NETWORK_ERROR, DEFUALT_MESSAGE_TYPE, e.getMessage());
        return null;
    }
}

From source file:com.epam.reportportal.apache.http.impl.conn.HttpClientConnectionOperator.java

public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }/*  www .  j  a va 2  s. c  om*/
    final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.apache.http.impl.conn.HttpClientConnectionOperator.java

public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }//from w  w  w  .ja v  a 2 s  .  c  o  m
    final InetAddress[] addresses = this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock.setSoTimeout(socketConfig.getSoTimeout());
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
            sock.setKeepAlive(socketConfig.isSoKeepAlive());
            final int linger = socketConfig.getSoLinger();
            if (linger >= 0) {
                sock.setSoLinger(linger > 0, linger);
            }
            conn.bind(sock);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection established " + conn);
            }
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.rss.DataCache.java

/** Add binary data entry into the cache.  Does NOT close the input stream when done!
*@param documentIdentifier is the document identifier (url).
*@param contentType is the content type for the data.
*@param dataStream is the data stream./* w  ww.  ja  v  a2s  .c  om*/
*@return the checksum value.
*/
public long addData(IProcessActivity activities, String documentIdentifier, String contentType,
        InputStream dataStream) throws ManifoldCFException, ServiceInterruption {
    // Create a temporary file; that's what we will cache
    try {
        File tempFile = File.createTempFile("_rsscache_", "tmp");
        try {
            // Causes memory leaks if left around; there's no way to release
            // the record specifying that the file should be deleted, even
            // after it's removed.  So disable this and live with the occasional
            // dangling file left as a result of shutdown or error. :-(
            // tempFile.deleteOnExit();
            ManifoldCF.addFile(tempFile);

            // Transfer data to temporary file
            long checkSum = 0L;
            OutputStream os = new FileOutputStream(tempFile);
            try {
                byte[] byteArray = new byte[65536];
                while (true) {
                    int amt;
                    try {
                        amt = dataStream.read(byteArray, 0, byteArray.length);
                    } catch (java.net.SocketTimeoutException e) {
                        Logging.connectors.warn(
                                "RSS: Socket timeout exception reading socket stream: " + e.getMessage(), e);
                        long currentTime = System.currentTimeMillis();
                        throw new ServiceInterruption("Read timeout: " + e.getMessage(), e,
                                currentTime + 300000L, currentTime + 12 * 60 * 60000L, -1, false);
                    } catch (ConnectTimeoutException e) {
                        Logging.connectors.warn(
                                "RSS: Connect timeout exception reading socket stream: " + e.getMessage(), e);
                        long currentTime = System.currentTimeMillis();
                        throw new ServiceInterruption("Read timeout: " + e.getMessage(), e,
                                currentTime + 300000L, currentTime + 12 * 60 * 60000L, -1, false);
                    } catch (InterruptedIOException e) {
                        throw new ManifoldCFException("Interrupted: " + e.getMessage(),
                                ManifoldCFException.INTERRUPTED);
                    } catch (IOException e) {
                        Logging.connectors.warn("RSS: IO exception reading socket stream: " + e.getMessage(),
                                e);
                        long currentTime = System.currentTimeMillis();
                        throw new ServiceInterruption("Read timeout: " + e.getMessage(), e,
                                currentTime + 300000L, currentTime + 12 * 60 * 60000L, -1, false);
                    }
                    if (amt == -1)
                        break;
                    int i = 0;
                    while (i < amt) {
                        byte x = byteArray[i++];
                        long bytevalue = (long) x;
                        checkSum = (checkSum << 5) ^ (checkSum >> 3) ^ (bytevalue << 2) ^ (bytevalue >> 3);
                    }

                    os.write(byteArray, 0, amt);
                    // Before we go 'round again, do a check
                    activities.checkJobStillActive();
                }
            } finally {
                os.close();
            }

            deleteData(documentIdentifier);

            synchronized (this) {
                cacheData.put(documentIdentifier, new DocumentData(tempFile, contentType));
            }

            return checkSum;
        } catch (IOException e) {
            ManifoldCF.deleteFile(tempFile);
            throw e;
        } catch (ServiceInterruption e) {
            ManifoldCF.deleteFile(tempFile);
            throw e;
        } catch (Error e) {
            ManifoldCF.deleteFile(tempFile);
            throw e;
        }
    } catch (java.net.SocketTimeoutException e) {
        throw new ManifoldCFException("Socket timeout exception creating temporary file: " + e.getMessage(), e);
    } catch (ConnectTimeoutException e) {
        throw new ManifoldCFException(
                "Socket connect timeout exception creating temporary file: " + e.getMessage(), e);
    } catch (InterruptedIOException e) {
        throw new ManifoldCFException("Interrupted: " + e.getMessage(), ManifoldCFException.INTERRUPTED);
    } catch (IOException e) {
        throw new ManifoldCFException("IO exception creating temporary file: " + e.getMessage(), e);
    }
}

From source file:com.newrelic.agent.deps.org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.java

@Override
public void connect(final ManagedHttpClientConnection conn, final HttpHost host,
        final InetSocketAddress localAddress, final int connectTimeout, final SocketConfig socketConfig,
        final HttpContext context) throws IOException {
    final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(context);
    final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName());
    if (sf == null) {
        throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported");
    }//w  ww . ja  va  2 s  . c  om
    final InetAddress[] addresses = host.getAddress() != null ? new InetAddress[] { host.getAddress() }
            : this.dnsResolver.resolve(host.getHostName());
    final int port = this.schemePortResolver.resolve(host);
    for (int i = 0; i < addresses.length; i++) {
        final InetAddress address = addresses[i];
        final boolean last = i == addresses.length - 1;

        Socket sock = sf.createSocket(context);
        sock.setSoTimeout(socketConfig.getSoTimeout());
        sock.setReuseAddress(socketConfig.isSoReuseAddress());
        sock.setTcpNoDelay(socketConfig.isTcpNoDelay());
        sock.setKeepAlive(socketConfig.isSoKeepAlive());
        final int linger = socketConfig.getSoLinger();
        if (linger >= 0) {
            sock.setSoLinger(true, linger);
        }
        conn.bind(sock);

        final InetSocketAddress remoteAddress = new InetSocketAddress(address, port);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connecting to " + remoteAddress);
        }
        try {
            sock = sf.connectSocket(connectTimeout, sock, host, remoteAddress, localAddress, context);
            conn.bind(sock);
            if (this.log.isDebugEnabled()) {
                this.log.debug("Connection established " + conn);
            }
            return;
        } catch (final SocketTimeoutException ex) {
            if (last) {
                throw new ConnectTimeoutException(ex, host, addresses);
            }
        } catch (final ConnectException ex) {
            if (last) {
                final String msg = ex.getMessage();
                if ("Connection timed out".equals(msg)) {
                    throw new ConnectTimeoutException(ex, host, addresses);
                } else {
                    throw new HttpHostConnectException(ex, host, addresses);
                }
            }
        } catch (final NoRouteToHostException ex) {
            if (last) {
                throw ex;
            }
        }
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connect to " + remoteAddress + " timed out. "
                    + "Connection will be retried using another IP address");
        }
    }
}

From source file:org.hyperic.hq.bizapp.agent.server.SSLConnectionListener.java

private SSLServerConnection handleNewConn(SSLSocket sock)
        throws AgentConnectionException, SocketTimeoutException {
    SSLServerConnection res;/* w  w w.ja  v a  2 s  .com*/
    InetAddress remoteAddr;
    TokenData token;
    String authToken;
    boolean doSave;

    remoteAddr = sock.getInetAddress();
    this.log.debug("Handling SSL connection from " + remoteAddr);
    res = new SSLServerConnection(sock);

    // Validate the actual auth token which is sent
    try {
        DataInputStream dIs;

        dIs = new DataInputStream(sock.getInputStream());

        this.log.debug("Starting to read authToken for SSL connection");
        authToken = dIs.readUTF();
        this.log.debug("Finished reading authToken for SSL connection");
    } catch (SocketTimeoutException exc) {
        throw exc;
    } catch (IOException exc) {
        throw new AgentConnectionException("Error negotiating auth: " + exc.getMessage(), exc);
    }

    // Set the token from pending to locked, if need be
    doSave = false;
    try {
        token = this.tokenManager.getToken(authToken);
    } catch (TokenNotFoundException exc) {
        this.log.error(
                "Rejecting client from " + remoteAddr + ": Passed an invalid auth token (" + authToken + ")",
                exc);
        // Due to 20 second expiration, the tokens in the manager
        // may not match what is in the tokendata.
        List l = this.tokenManager.getTokens();
        for (Iterator i = l.iterator(); i.hasNext();) {
            TokenData data = (TokenData) i.next();
            this.log.debug("Token: " + data.getToken() + ":" + data.getCreateTime() + ":"
                    + (data.isLocked() ? "locked" : "pending"));
        }

        try {
            res.readCommand();
            res.sendErrorResponse("Unauthorized");
        } catch (AgentConnectionException iExc) {
            log.debug(iExc, iExc);
        } catch (EOFException e) {
            log.debug(e, e);
        }

        throw new AgentConnectionException("Client from " + remoteAddr + " unauthorized");
    }

    if (!token.isLocked()) {
        try {
            this.log.info("Locking auth token");
            this.tokenManager.setTokenLocked(token, true);
            doSave = true;
        } catch (TokenNotFoundException exc) {
            // This should never occur
            this.log.error("Error setting token '" + token + "' to " + "locked state -- it no longer exists");
        }
    }

    // If set the token, re-store the data.
    if (doSave) {
        try {
            this.tokenManager.store();
        } catch (IOException exc) {
            this.log.error("Error storing token data: " + exc.getMessage());
        }
    }
    this.log.debug("Done connecting SSL");
    return res;
}

From source file:com.mirth.connect.connectors.mllp.protocols.LlpProtocol.java

private byte[] readLLP(InputStream is) throws IOException {

    // ast: new function to process the MLLP protocol
    // ast: wrapper for the reader
    String charset = _mllpConnector.getCharsetEncoding();
    UtilReader myReader = new UtilReader(is, charset);

    boolean end_of_message = false;

    int c = 0;//from  w w w .  j av  a  2  s .  com
    try {
        c = myReader.read();
    } catch (SocketException e) {
        logger.info(
                "SocketException on read() attempt.  Socket appears to have been closed: " + e.getMessage());
        return null;
    } catch (SocketTimeoutException ste) {
        logger.info("SocketTimeoutException on read() attempt.  Socket appears to have been closed: "
                + ste.getMessage());
        return null;
    }

    // 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 != START_MESSAGE) && (c != -1)) {
        try {
            c = myReader.read();
        } catch (Exception e) {
            c = -1;
        }
    }

    if (c == -1) { // End of stream reached without start of message character.
        String message = myReader.toString();
        logger.error("Bytes received violate the MLLP: no start of message indicator received.\r\n" + message);
        return null;
    }

    myReader.append((char) c);

    while (!end_of_message) {
        c = myReader.read();

        if (c == -1) {
            logger.error("Message violates the " + "minimal lower protocol: message terminated without "
                    + "a terminating character.");
            return null;
        }
        myReader.append((char) c);
        if (c == END_MESSAGE) {

            if (END_OF_RECORD != 0) {
                // subsequent character should be a carriage return
                try {
                    c = myReader.read();
                    if (END_OF_RECORD != 0 && c != END_OF_RECORD) {
                        logger.error(
                                "Message terminator was: " + c + "  Expected terminator: " + END_OF_RECORD);
                        return null;
                    }
                    myReader.append((char) c);
                } catch (SocketException e) {
                    logger.info("SocketException on read() attempt.  Socket appears to have been closed: "
                            + e.getMessage());
                } catch (SocketTimeoutException ste) {
                    logger.info(
                            "SocketTimeoutException on read() attempt.  Socket appears to have been closed: "
                                    + ste.getMessage());
                }
            }
            end_of_message = true;
        }
    } // end while

    return myReader.getBytes();
}

From source file:org.mythdroid.services.JSONClient.java

private JSONObject Request(HttpUriRequest req) throws IOException {

    req.setHeader("Accept", "application/json"); //$NON-NLS-1$ //$NON-NLS-2$
    LogUtil.debug("JSON request: " + req.getURI().toString()); //$NON-NLS-1$

    String res = null;//from w w  w  .  ja  va  2s.c o  m

    try {
        res = new HttpFetcher(req, Globals.muxConns).getContent();
    } catch (SocketTimeoutException e) {
        throw new IOException(Messages.getString("JSONClient.0") + //$NON-NLS-1$
                req.getURI().getHost() + ":" + req.getURI().getPort() //$NON-NLS-1$
        );
    } catch (ClientProtocolException e) {
        ErrUtil.logErr(e);
        throw new IOException(e.getMessage());
    }

    LogUtil.debug("JSON response: " + res); //$NON-NLS-1$

    try {
        return new JSONObject(res);
    } catch (JSONException e) {
        ErrUtil.logErr(e);
        throw new IOException(e.getMessage());
    }

}