Search in sources :

Example 66 with SocketTimeoutException

use of java.net.SocketTimeoutException in project quorrabot by GloriousEggroll.

the class DonationHandlerAPI method GetData.

@SuppressWarnings({ "null", "SleepWhileInLoop", "UseSpecificCatch" })
private JSONObject GetData(request_type type, String url, String post) {
    Date start = new Date();
    Date preconnect = start;
    Date postconnect = start;
    Date prejson = start;
    Date postjson = start;
    JSONObject j = new JSONObject("{}");
    BufferedInputStream i = null;
    String rawcontent = "";
    int available = 0;
    int responsecode = 0;
    long cl = 0;
    try {
        URL u = new URL(url);
        HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
        c.setRequestMethod(type.name());
        c.setUseCaches(false);
        c.setDefaultUseCaches(false);
        c.setConnectTimeout(5000);
        c.setReadTimeout(5000);
        c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.52 Safari/537.36 QuorraBot/2015");
        c.setRequestProperty("Content-Type", "application/json-rpc");
        c.setRequestProperty("Content-length", "0");
        if (!post.isEmpty()) {
            c.setDoOutput(true);
        }
        preconnect = new Date();
        c.connect();
        postconnect = new Date();
        if (!post.isEmpty()) {
            try (BufferedOutputStream o = new BufferedOutputStream(c.getOutputStream())) {
                IOUtils.write(post, o);
            }
        }
        String content;
        cl = c.getContentLengthLong();
        responsecode = c.getResponseCode();
        if (c.getResponseCode() == 200) {
            i = new BufferedInputStream(c.getInputStream());
        } else {
            i = new BufferedInputStream(c.getErrorStream());
        }
        /*
             * if (i != null) { available = i.available();
             *
             * while (available == 0 && (new Date().getTime() -
             * postconnect.getTime()) < 450) { Thread.sleep(500); available =
             * i.available(); }
             *
             * if (available == 0) { i = new
             * BufferedInputStream(c.getErrorStream());
             *
             * if (i != null) { available = i.available(); } } }
             *
             * if (available == 0) { content = "{}"; } else { content =
             * IOUtils.toString(i, c.getContentEncoding()); }
             */
        content = IOUtils.toString(i, c.getContentEncoding());
        rawcontent = content;
        prejson = new Date();
        j = new JSONObject(content);
        j.put("_success", true);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", c.getResponseCode());
        j.put("_available", available);
        j.put("_exception", "");
        j.put("_exceptionMessage", "");
        j.put("_content", content);
        postjson = new Date();
    } catch (JSONException ex) {
        if (ex.getMessage().contains("A JSONObject text must begin with")) {
            j = new JSONObject("{}");
            j.put("_success", true);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "MalformedJSONData (HTTP " + responsecode + ")");
            j.put("_exceptionMessage", "");
            j.put("_content", rawcontent);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (NullPointerException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    } catch (MalformedURLException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "MalformedURLException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (SocketTimeoutException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "SocketTimeoutException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (IOException ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "IOException");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    } catch (Exception ex) {
        j.put("_success", false);
        j.put("_type", type.name());
        j.put("_url", url);
        j.put("_post", post);
        j.put("_http", 0);
        j.put("_available", available);
        j.put("_exception", "Exception [" + ex.getClass().getName() + "]");
        j.put("_exceptionMessage", ex.getMessage());
        j.put("_content", "");
        if (Quorrabot.enableDebugging) {
            com.gmt2001.Console.err.printStackTrace(ex);
        } else {
            com.gmt2001.Console.err.logStackTrace(ex);
        }
    }
    if (i != null) {
        try {
            i.close();
        } catch (IOException ex) {
            j.put("_success", false);
            j.put("_type", type.name());
            j.put("_url", url);
            j.put("_post", post);
            j.put("_http", 0);
            j.put("_available", available);
            j.put("_exception", "IOException");
            j.put("_exceptionMessage", ex.getMessage());
            j.put("_content", "");
            if (Quorrabot.enableDebugging) {
                com.gmt2001.Console.err.printStackTrace(ex);
            } else {
                com.gmt2001.Console.err.logStackTrace(ex);
            }
        }
    }
    if (Quorrabot.enableDebugging) {
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Timers " + (preconnect.getTime() - start.getTime()) + " " + (postconnect.getTime() - start.getTime()) + " " + (prejson.getTime() - start.getTime()) + " " + (postjson.getTime() - start.getTime()) + " " + start.toString() + " " + postjson.toString());
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData Exception " + j.getString("_exception") + " " + j.getString("_exceptionMessage"));
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData HTTP/Available " + j.getInt("_http") + "(" + responsecode + ")/" + j.getInt("_available") + "(" + cl + ")");
        com.gmt2001.Console.out.println(">>>[DEBUG] DonationHandlerAPI.GetData RawContent[0,100] " + j.getString("_content").substring(0, Math.min(100, j.getString("_content").length())));
    }
    return j;
}
Also used : MalformedURLException(java.net.MalformedURLException) JSONException(org.json.JSONException) IOException(java.io.IOException) Date(java.util.Date) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) JSONException(org.json.JSONException) SocketTimeoutException(java.net.SocketTimeoutException) SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(org.json.JSONObject) BufferedInputStream(java.io.BufferedInputStream) BufferedOutputStream(java.io.BufferedOutputStream) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 67 with SocketTimeoutException

use of java.net.SocketTimeoutException in project fc-java-sdk by aliyun.

the class DefaultFcClient method doAction.

public HttpResponse doAction(HttpRequest request, String form, String method) throws ClientException, ServerException {
    request.validate();
    try {
        PrepareUrl prepareUrl = signRequest(request, form, method);
        int retryTimes = 1;
        HttpResponse response = HttpResponse.getResponse(prepareUrl.getUrl(), prepareUrl.getHeader(), request, method, config.getConnectTimeoutMillis(), config.getReadTimeoutMillis());
        while (500 <= response.getStatus() && AUTO_RETRY && retryTimes < MAX_RETRIES) {
            prepareUrl = signRequest(request, form, method);
            response = HttpResponse.getResponse(prepareUrl.getUrl(), prepareUrl.getHeader(), request, method, config.getConnectTimeoutMillis(), config.getReadTimeoutMillis());
            retryTimes++;
        }
        if (response.getStatus() >= 500) {
            String requestId = response.getHeaderValue(HeaderKeys.REQUEST_ID);
            String stringContent = response.getContent() == null ? "" : new String(response.getContent());
            ServerException se;
            try {
                se = new Gson().fromJson(stringContent, ServerException.class);
            } catch (JsonParseException e) {
                se = new ServerException("InternalServiceError", "Failed to parse response content", requestId);
            }
            se.setStatusCode(response.getStatus());
            se.setRequestId(requestId);
            throw se;
        } else if (response.getStatus() >= 300) {
            ClientException ce;
            if (response.getContent() == null) {
                ce = new ClientException("SDK.ServerUnreachable", "Failed to get response content from server");
            } else {
                try {
                    ce = new Gson().fromJson(new String(response.getContent()), ClientException.class);
                } catch (JsonParseException e) {
                    ce = new ClientException("SDK.ResponseNotParsable", "Failed to parse response content", e);
                }
            }
            if (ce == null) {
                ce = new ClientException("SDK.UnknownError", "Unknown client error");
            }
            ce.setStatusCode(response.getStatus());
            ce.setRequestId(response.getHeaderValue(HeaderKeys.REQUEST_ID));
            throw ce;
        }
        return response;
    } catch (InvalidKeyException exp) {
        throw new ClientException("SDK.InvalidAccessSecret", "Speicified access secret is not valid.");
    } catch (SocketTimeoutException exp) {
        throw new ClientException("SDK.ServerUnreachable", "SocketTimeoutException has occurred on a socket read or accept.");
    } catch (IOException exp) {
        throw new ClientException("SDK.ServerUnreachable", "Server unreachable: " + exp.toString());
    } catch (NoSuchAlgorithmException exp) {
        throw new ClientException("SDK.InvalidMD5Algorithm", "MD5 hash is not supported by client side.");
    }
}
Also used : PrepareUrl(com.aliyuncs.fc.model.PrepareUrl) ServerException(com.aliyuncs.fc.exceptions.ServerException) SocketTimeoutException(java.net.SocketTimeoutException) HttpResponse(com.aliyuncs.fc.http.HttpResponse) Gson(com.google.gson.Gson) ClientException(com.aliyuncs.fc.exceptions.ClientException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JsonParseException(com.google.gson.JsonParseException) InvalidKeyException(java.security.InvalidKeyException)

Example 68 with SocketTimeoutException

use of java.net.SocketTimeoutException in project lucene-solr by apache.

the class RecoveryStrategy method sendPrepRecoveryCmd.

private final void sendPrepRecoveryCmd(String leaderBaseUrl, String leaderCoreName, Slice slice) throws SolrServerException, IOException, InterruptedException, ExecutionException {
    WaitForState prepCmd = new WaitForState();
    prepCmd.setCoreName(leaderCoreName);
    prepCmd.setNodeName(zkController.getNodeName());
    prepCmd.setCoreNodeName(coreZkNodeName);
    prepCmd.setState(Replica.State.RECOVERING);
    prepCmd.setCheckLive(true);
    prepCmd.setOnlyIfLeader(true);
    final Slice.State state = slice.getState();
    if (state != Slice.State.CONSTRUCTION && state != Slice.State.RECOVERY && state != Slice.State.RECOVERY_FAILED) {
        prepCmd.setOnlyIfLeaderActive(true);
    }
    final int maxTries = 30;
    for (int numTries = 0; numTries < maxTries; numTries++) {
        try {
            sendPrepRecoveryCmd(leaderBaseUrl, prepCmd);
            break;
        } catch (ExecutionException e) {
            if (e.getCause() instanceof SolrServerException) {
                SolrServerException solrException = (SolrServerException) e.getCause();
                if (solrException.getRootCause() instanceof SocketTimeoutException && numTries < maxTries) {
                    LOG.warn("Socket timeout on send prep recovery cmd, retrying.. ");
                    continue;
                }
            }
            throw e;
        }
    }
}
Also used : WaitForState(org.apache.solr.client.solrj.request.CoreAdminRequest.WaitForState) SocketTimeoutException(java.net.SocketTimeoutException) Slice(org.apache.solr.common.cloud.Slice) SolrServerException(org.apache.solr.client.solrj.SolrServerException) ExecutionException(java.util.concurrent.ExecutionException)

Example 69 with SocketTimeoutException

use of java.net.SocketTimeoutException in project lucene-solr by apache.

the class LBHttpSolrClient method doRequest.

protected Exception doRequest(HttpSolrClient client, Req req, Rsp rsp, boolean isNonRetryable, boolean isZombie, String zombieKey) throws SolrServerException, IOException {
    Exception ex = null;
    try {
        rsp.server = client.getBaseURL();
        rsp.rsp = client.request(req.getRequest(), (String) null);
        if (isZombie) {
            zombieServers.remove(zombieKey);
        }
    } catch (SolrException e) {
        // unless it's an update - then we only retry on connect exception
        if (!isNonRetryable && RETRY_CODES.contains(e.code())) {
            ex = (!isZombie) ? addZombie(client, e) : e;
        } else {
            // Server is alive but the request was likely malformed or invalid
            if (isZombie) {
                zombieServers.remove(zombieKey);
            }
            throw e;
        }
    } catch (SocketException e) {
        if (!isNonRetryable || e instanceof ConnectException) {
            ex = (!isZombie) ? addZombie(client, e) : e;
        } else {
            throw e;
        }
    } catch (SocketTimeoutException e) {
        if (!isNonRetryable) {
            ex = (!isZombie) ? addZombie(client, e) : e;
        } else {
            throw e;
        }
    } catch (SolrServerException e) {
        Throwable rootCause = e.getRootCause();
        if (!isNonRetryable && rootCause instanceof IOException) {
            ex = (!isZombie) ? addZombie(client, e) : e;
        } else if (isNonRetryable && rootCause instanceof ConnectException) {
            ex = (!isZombie) ? addZombie(client, e) : e;
        } else {
            throw e;
        }
    } catch (Exception e) {
        throw new SolrServerException(e);
    }
    return ex;
}
Also used : SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) IOException(java.io.IOException) SolrServerException(org.apache.solr.client.solrj.SolrServerException) SolrException(org.apache.solr.common.SolrException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SolrException(org.apache.solr.common.SolrException) ConnectException(java.net.ConnectException)

Example 70 with SocketTimeoutException

use of java.net.SocketTimeoutException in project maven-plugins by apache.

the class JavadocUtilTest method testIsValidPackageList.

/**
     * Method to test isValidPackageList()
     *
     * @throws Exception if any
     */
public void testIsValidPackageList() throws Exception {
    Settings settings = null;
    Proxy proxy;
    URL url = null;
    URL wrongUrl;
    try {
        JavadocUtil.isValidPackageList(url, settings, false);
        fail();
    } catch (IllegalArgumentException e) {
        assertTrue(true);
    }
    url = new File(getBasedir(), "/pom.xml").toURL();
    assertTrue(JavadocUtil.isValidPackageList(url, settings, false));
    try {
        assertFalse(JavadocUtil.isValidPackageList(url, settings, true));
    } catch (IOException e) {
        assertTrue(true);
    }
    url = this.getClass().getResource("/JavadocUtilTest-package-list.txt").toURI().toURL();
    assertTrue(JavadocUtil.isValidPackageList(url, settings, true));
    url = new URL("http://maven.apache.org/plugins/maven-javadoc-plugin/apidocs/package-list");
    assertTrue(JavadocUtil.isValidPackageList(url, settings, true));
    wrongUrl = new URL("http://maven.apache.org/plugins/maven-javadoc-plugin/apidocs/package-list2");
    try {
        JavadocUtil.isValidPackageList(wrongUrl, settings, false);
        fail();
    } catch (IOException e) {
        assertTrue(true);
    }
    // real proxy
    ProxyServer proxyServer = null;
    AuthAsyncProxyServlet proxyServlet;
    try {
        proxyServlet = new AuthAsyncProxyServlet();
        proxyServer = new ProxyServer(proxyServlet);
        proxyServer.start();
        settings = new Settings();
        assertTrue(JavadocUtil.isValidPackageList(url, settings, true));
        try {
            JavadocUtil.isValidPackageList(wrongUrl, settings, false);
            fail();
        } catch (IOException e) {
            assertTrue(true);
        }
    } finally {
        if (proxyServer != null) {
            proxyServer.stop();
        }
    }
    Map<String, String> authentications = new HashMap<String, String>();
    authentications.put("foo", "bar");
    // wrong auth
    try {
        proxyServlet = new AuthAsyncProxyServlet(authentications);
        proxyServer = new ProxyServer(proxyServlet);
        proxyServer.start();
        settings = new Settings();
        proxy = new Proxy();
        proxy.setActive(true);
        proxy.setHost(proxyServer.getHostName());
        proxy.setPort(proxyServer.getPort());
        proxy.setProtocol("http");
        settings.addProxy(proxy);
        JavadocUtil.isValidPackageList(url, settings, false);
        fail();
    } catch (FileNotFoundException e) {
        assertTrue(true);
    } finally {
        if (proxyServer != null) {
            proxyServer.stop();
        }
    }
    // auth proxy
    try {
        proxyServlet = new AuthAsyncProxyServlet(authentications);
        proxyServer = new ProxyServer(proxyServlet);
        proxyServer.start();
        settings = new Settings();
        proxy = new Proxy();
        proxy.setActive(true);
        proxy.setHost(proxyServer.getHostName());
        proxy.setPort(proxyServer.getPort());
        proxy.setProtocol("http");
        proxy.setUsername("foo");
        proxy.setPassword("bar");
        settings.addProxy(proxy);
        assertTrue(JavadocUtil.isValidPackageList(url, settings, true));
        try {
            JavadocUtil.isValidPackageList(wrongUrl, settings, false);
            fail();
        } catch (IOException e) {
            assertTrue(true);
        }
    } finally {
        if (proxyServer != null) {
            proxyServer.stop();
        }
    }
    // timeout
    try {
        // more than 2000, see fetchURL
        proxyServlet = new AuthAsyncProxyServlet(authentications, 3000);
        proxyServer = new ProxyServer(proxyServlet);
        proxyServer.start();
        settings = new Settings();
        proxy = new Proxy();
        proxy.setActive(true);
        proxy.setHost(proxyServer.getHostName());
        proxy.setPort(proxyServer.getPort());
        proxy.setProtocol("http");
        proxy.setUsername("foo");
        proxy.setPassword("bar");
        settings.addProxy(proxy);
        JavadocUtil.isValidPackageList(url, settings, true);
        fail();
    } catch (SocketTimeoutException e) {
        assertTrue(true);
    } finally {
        if (proxyServer != null) {
            proxyServer.stop();
        }
    }
    // nonProxyHosts
    try {
        proxyServlet = new AuthAsyncProxyServlet(authentications);
        proxyServer = new ProxyServer(proxyServlet);
        proxyServer.start();
        settings = new Settings();
        proxy = new Proxy();
        proxy.setActive(true);
        proxy.setHost(proxyServer.getHostName());
        proxy.setPort(proxyServer.getPort());
        proxy.setProtocol("http");
        proxy.setUsername("foo");
        proxy.setPassword("bar");
        proxy.setNonProxyHosts("maven.apache.org");
        settings.addProxy(proxy);
        assertTrue(JavadocUtil.isValidPackageList(url, settings, true));
    } finally {
        if (proxyServer != null) {
            proxyServer.stop();
        }
    }
}
Also used : HashMap(java.util.HashMap) AuthAsyncProxyServlet(org.apache.maven.plugin.javadoc.ProxyServer.AuthAsyncProxyServlet) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) URL(java.net.URL) Proxy(org.apache.maven.settings.Proxy) SocketTimeoutException(java.net.SocketTimeoutException) File(java.io.File) Settings(org.apache.maven.settings.Settings)

Aggregations

SocketTimeoutException (java.net.SocketTimeoutException)721 IOException (java.io.IOException)420 Test (org.junit.Test)139 Socket (java.net.Socket)103 SocketException (java.net.SocketException)99 ServerSocket (java.net.ServerSocket)79 InputStream (java.io.InputStream)77 ConnectException (java.net.ConnectException)70 UnknownHostException (java.net.UnknownHostException)64 InetSocketAddress (java.net.InetSocketAddress)60 URL (java.net.URL)51 EOFException (java.io.EOFException)48 HttpURLConnection (java.net.HttpURLConnection)47 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)42 InterruptedIOException (java.io.InterruptedIOException)40 ArrayList (java.util.ArrayList)40 MalformedURLException (java.net.MalformedURLException)38 InputStreamReader (java.io.InputStreamReader)37 HashMap (java.util.HashMap)36 OutputStream (java.io.OutputStream)35