Search in sources :

Example 41 with ConnectException

use of java.net.ConnectException in project intellij-community by JetBrains.

the class SocketLock method tryActivate.

@NotNull
private ActivateStatus tryActivate(int portNumber, @NotNull Collection<String> paths, @NotNull String[] args) {
    log("trying: port=%s", portNumber);
    args = checkForJetBrainsProtocolCommand(args);
    try {
        try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), portNumber)) {
            socket.setSoTimeout(1000);
            boolean result = false;
            @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") DataInputStream in = new DataInputStream(socket.getInputStream());
            while (true) {
                try {
                    String path = in.readUTF();
                    log("read: path=%s", path);
                    if (PATHS_EOT_RESPONSE.equals(path)) {
                        break;
                    } else if (paths.contains(path)) {
                        // don't break - read all input
                        result = true;
                    }
                } catch (IOException e) {
                    log("read: %s", e.getMessage());
                    break;
                }
            }
            if (result) {
                try {
                    String token = FileUtil.loadFile(new File(mySystemPath, TOKEN_FILE));
                    @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                    out.writeUTF(ACTIVATE_COMMAND + token + "\0" + new File(".").getAbsolutePath() + "\0" + StringUtil.join(args, "\0"));
                    out.flush();
                    String response = in.readUTF();
                    log("read: response=%s", response);
                    if (response.equals(OK_RESPONSE)) {
                        if (isShutdownCommand()) {
                            printPID(portNumber);
                        }
                        return ActivateStatus.ACTIVATED;
                    }
                } catch (IOException e) {
                    log(e);
                }
                return ActivateStatus.CANNOT_ACTIVATE;
            }
        }
    } catch (ConnectException e) {
        log("%s (stale port file?)", e.getMessage());
    } catch (IOException e) {
        log(e);
    }
    return ActivateStatus.NO_INSTANCE;
}
Also used : Socket(java.net.Socket) ConnectException(java.net.ConnectException) NotNull(org.jetbrains.annotations.NotNull)

Example 42 with ConnectException

use of java.net.ConnectException in project adempiere by adempiere.

the class Worker method run.

/**
	 *  Worker: Read available Online Help Pages
	 */
public void run() {
    if (m_links == null)
        return;
    URL url = null;
    try {
        url = new URL(m_urlString);
    } catch (Exception e) {
        System.err.println("OnlineHelp.Worker.run (url) - " + e);
    }
    if (url == null)
        return;
    //  Read Reference Page
    try {
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        HTMLEditorKit kit = new HTMLEditorKit();
        HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument();
        doc.putProperty("IgnoreCharsetDirective", new Boolean(true));
        kit.read(new InputStreamReader(is), doc, 0);
        //  Get The Links to the Help Pages
        HTMLDocument.Iterator it = doc.getIterator(HTML.Tag.A);
        Object target = null;
        Object href = null;
        while (it != null && it.isValid()) {
            AttributeSet as = it.getAttributes();
            //  key keys
            if (target == null || href == null) {
                Enumeration en = as.getAttributeNames();
                while (en.hasMoreElements()) {
                    Object o = en.nextElement();
                    if (target == null && o.toString().equals("target"))
                        //	javax.swing.text.html.HTML$Attribute
                        target = o;
                    else if (href == null && o.toString().equals("href"))
                        href = o;
                }
            }
            if (target != null && "Online".equals(as.getAttribute(target))) {
                //  Format: /help/<AD_Window_ID>/index.html
                String hrefString = (String) as.getAttribute(href);
                if (hrefString != null) {
                    try {
                        //		System.err.println(hrefString);
                        String AD_Window_ID = hrefString.substring(hrefString.indexOf('/', 1), hrefString.lastIndexOf('/'));
                        m_links.put(AD_Window_ID, hrefString);
                    } catch (Exception e) {
                        System.err.println("OnlineHelp.Worker.run (help) - " + e);
                    }
                }
            }
            it.next();
        }
        is.close();
    } catch (ConnectException e) {
    //	System.err.println("OnlineHelp.Worker.run URL=" + url + " - " + e);
    } catch (UnknownHostException uhe) {
    //	System.err.println("OnlineHelp.Worker.run " + uhe);
    } catch (Exception e) {
        System.err.println("OnlineHelp.Worker.run (e) " + e);
    //	e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("OnlineHelp.Worker.run (t) " + t);
    //	t.printStackTrace();
    }
//	System.out.println("OnlineHelp - Links=" + m_links.size());
}
Also used : Enumeration(java.util.Enumeration) InputStreamReader(java.io.InputStreamReader) UnknownHostException(java.net.UnknownHostException) InputStream(java.io.InputStream) HTMLDocument(javax.swing.text.html.HTMLDocument) HTMLEditorKit(javax.swing.text.html.HTMLEditorKit) URL(java.net.URL) UnknownHostException(java.net.UnknownHostException) ConnectException(java.net.ConnectException) URLConnection(java.net.URLConnection) AttributeSet(javax.swing.text.AttributeSet) ConnectException(java.net.ConnectException)

Example 43 with ConnectException

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

the class HttpShardHandler method submit.

@Override
public void submit(final ShardRequest sreq, final String shard, final ModifiableSolrParams params) {
    // do this outside of the callable for thread safety reasons
    final List<String> urls = getURLs(shard);
    Callable<ShardResponse> task = () -> {
        ShardResponse srsp = new ShardResponse();
        if (sreq.nodeName != null) {
            srsp.setNodeName(sreq.nodeName);
        }
        srsp.setShardRequest(sreq);
        srsp.setShard(shard);
        SimpleSolrResponse ssr = new SimpleSolrResponse();
        srsp.setSolrResponse(ssr);
        long startTime = System.nanoTime();
        try {
            // use default (currently javabin)
            params.remove(CommonParams.WT);
            params.remove(CommonParams.VERSION);
            QueryRequest req = makeQueryRequest(sreq, params, shard);
            req.setMethod(SolrRequest.METHOD.POST);
            // if there are no shards available for a slice, urls.size()==0
            if (urls.size() == 0) {
                // all of the servers for a shard are down.
                throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "no servers hosting shard: " + shard);
            }
            if (urls.size() <= 1) {
                String url = urls.get(0);
                srsp.setShardAddress(url);
                try (SolrClient client = new Builder(url).withHttpClient(httpClient).build()) {
                    ssr.nl = client.request(req);
                }
            } else {
                LBHttpSolrClient.Rsp rsp = httpShardHandlerFactory.makeLoadBalancedRequest(req, urls);
                ssr.nl = rsp.getResponse();
                srsp.setShardAddress(rsp.getServer());
            }
        } catch (ConnectException cex) {
            //????
            srsp.setException(cex);
        } catch (Exception th) {
            srsp.setException(th);
            if (th instanceof SolrException) {
                srsp.setResponseCode(((SolrException) th).code());
            } else {
                srsp.setResponseCode(-1);
            }
        }
        ssr.elapsedTime = TimeUnit.MILLISECONDS.convert(System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
        return transfomResponse(sreq, srsp, shard);
    };
    try {
        if (shard != null) {
            MDC.put("ShardRequest.shards", shard);
        }
        if (urls != null && !urls.isEmpty()) {
            MDC.put("ShardRequest.urlList", urls.toString());
        }
        pending.add(completionService.submit(task));
    } finally {
        MDC.remove("ShardRequest.shards");
        MDC.remove("ShardRequest.urlList");
    }
}
Also used : QueryRequest(org.apache.solr.client.solrj.request.QueryRequest) SolrQueryRequest(org.apache.solr.request.SolrQueryRequest) SolrClient(org.apache.solr.client.solrj.SolrClient) LBHttpSolrClient(org.apache.solr.client.solrj.impl.LBHttpSolrClient) Builder(org.apache.solr.client.solrj.impl.HttpSolrClient.Builder) SolrException(org.apache.solr.common.SolrException) SolrException(org.apache.solr.common.SolrException) ConnectException(java.net.ConnectException) ExecutionException(java.util.concurrent.ExecutionException) ConnectException(java.net.ConnectException)

Example 44 with ConnectException

use of java.net.ConnectException in project ignite by apache.

the class RestExecutor method sendRequest.

/** */
private RestResult sendRequest(boolean demo, String path, Map<String, Object> params, String mtd, Map<String, Object> headers, String body) throws IOException {
    if (demo && AgentClusterDemo.getDemoUrl() == null) {
        try {
            AgentClusterDemo.tryStart().await();
        } catch (InterruptedException ignore) {
            throw new IllegalStateException("Failed to execute request because of embedded node for demo mode is not started yet.");
        }
    }
    String url = demo ? AgentClusterDemo.getDemoUrl() : nodeUrl;
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    if (path != null)
        urlBuilder.addPathSegment(path);
    final Request.Builder reqBuilder = new Request.Builder();
    if (headers != null) {
        for (Map.Entry<String, Object> entry : headers.entrySet()) if (entry.getValue() != null)
            reqBuilder.addHeader(entry.getKey(), entry.getValue().toString());
    }
    if ("GET".equalsIgnoreCase(mtd)) {
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null)
                    urlBuilder.addQueryParameter(entry.getKey(), entry.getValue().toString());
            }
        }
    } else if ("POST".equalsIgnoreCase(mtd)) {
        if (body != null) {
            MediaType contentType = MediaType.parse("text/plain");
            reqBuilder.post(RequestBody.create(contentType, body));
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if (entry.getValue() != null)
                        formBody.add(entry.getKey(), entry.getValue().toString());
                }
            }
            reqBuilder.post(formBody.build());
        }
    } else
        throw new IllegalArgumentException("Unknown HTTP-method: " + mtd);
    reqBuilder.url(urlBuilder.build());
    try (Response resp = httpClient.newCall(reqBuilder.build()).execute()) {
        String content = resp.body().string();
        if (resp.isSuccessful()) {
            JsonNode node = mapper.readTree(content);
            int status = node.get("successStatus").asInt();
            switch(status) {
                case STATUS_SUCCESS:
                    return RestResult.success(node.get("response").toString());
                default:
                    return RestResult.fail(status, node.get("error").asText());
            }
        }
        if (resp.code() == 401)
            return RestResult.fail(STATUS_AUTH_FAILED, "Failed to authenticate in grid. Please check agent\'s login and password or node port.");
        return RestResult.fail(STATUS_FAILED, "Failed connect to node and execute REST command.");
    } catch (ConnectException ignore) {
        throw new ConnectException("Failed connect to node and execute REST command [url=" + urlBuilder + "]");
    }
}
Also used : Request(okhttp3.Request) FormBody(okhttp3.FormBody) JsonNode(com.fasterxml.jackson.databind.JsonNode) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) ConnectException(java.net.ConnectException)

Example 45 with ConnectException

use of java.net.ConnectException 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)

Aggregations

ConnectException (java.net.ConnectException)521 IOException (java.io.IOException)211 Socket (java.net.Socket)84 SocketTimeoutException (java.net.SocketTimeoutException)69 Test (org.junit.Test)69 UnknownHostException (java.net.UnknownHostException)57 InetSocketAddress (java.net.InetSocketAddress)56 WebServiceException (javax.xml.ws.WebServiceException)48 SOAPFaultException (javax.xml.ws.soap.SOAPFaultException)48 ErrorCode (org.olat.modules.vitero.model.ErrorCode)48 FileNotFoundException (java.io.FileNotFoundException)39 URL (java.net.URL)36 InputStream (java.io.InputStream)33 NoRouteToHostException (java.net.NoRouteToHostException)33 SocketException (java.net.SocketException)33 ArrayList (java.util.ArrayList)31 InetAddress (java.net.InetAddress)29 InputStreamReader (java.io.InputStreamReader)28 OutputStream (java.io.OutputStream)28 HttpURLConnection (java.net.HttpURLConnection)28