Search in sources :

Example 41 with UnknownHostException

use of java.net.UnknownHostException in project databus by linkedin.

the class DatabusV2ClusterRegistrationImpl method start.

@Override
public synchronized boolean start() throws IllegalStateException, DatabusClientException {
    if (_state == RegistrationState.INIT || _state == RegistrationState.DEREGISTERED) {
        String errMsg = "Registration (" + _id + ") cannot be started from its current state, which is " + _state + " .It may only be started from REGISTERED or SHUTDOWN state";
        _log.error(errMsg);
        throw new IllegalStateException(errMsg);
    }
    if (_state.isRunning()) {
        _log.info("Registration (" + _id + ") already started !!");
        return false;
    }
    String host = null;
    try {
        host = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        _log.error("Unable to fetch the local hostname !! Trying to fetch IP Address !!", e);
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e1) {
            _log.error("Unable to fetch the local IP Address too !! Giving up", e1);
            host = "UNKNOWN_HOST";
        }
    }
    /**
     *  The id below has to be unique within a given cluster. HttpPort is used to get a unique name for service colocated in a single box.
     *  The Container id is not necessarily a sufficient differentiating factor.
     */
    String id = host + "-" + _client.getContainerStaticConfig().getHttpPort() + "-" + _client.getContainerStaticConfig().getId();
    try {
        _cluster = createCluster();
        _cluster.start();
    } catch (Exception e) {
        _log.fatal("Got exception while trying to create the cluster with id (" + id + ")", e);
        throw new DatabusClientException(e);
    }
    initializeStatsCollectors();
    _log.info("Dabatus cluster object created : " + _cluster + " with id :" + id);
    _clusterMember = _cluster.addMember(id, this);
    boolean joined = _clusterMember.join();
    if (!joined) {
        _log.fatal("Unable to join the cluster " + _clusterInfo);
        throw new DatabusClientException("Unable to join the cluster :" + _clusterInfo);
    }
    _state = RegistrationState.STARTED;
    activatePartitions();
    return true;
}
Also used : UnknownHostException(java.net.UnknownHostException) DatabusException(com.linkedin.databus2.core.DatabusException) InvalidConfigException(com.linkedin.databus.core.util.InvalidConfigException) ClusterCheckpointException(com.linkedin.databus.client.pub.ClusterCheckpointPersistenceProvider.ClusterCheckpointException) UnknownHostException(java.net.UnknownHostException) DatabusClientException(com.linkedin.databus.client.pub.DatabusClientException) DatabusClientException(com.linkedin.databus.client.pub.DatabusClientException)

Example 42 with UnknownHostException

use of java.net.UnknownHostException in project okhttp by square.

the class URLConnectionTest method urlHostWithNul.

@Test
public void urlHostWithNul() throws Exception {
    URLConnection urlConnection = urlFactory.open(new URL("http://host/"));
    try {
        urlConnection.getInputStream();
        fail();
    } catch (UnknownHostException expected) {
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) HttpURLConnection(java.net.HttpURLConnection) OkHttpURLConnection(okhttp3.internal.huc.OkHttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) URL(java.net.URL) Test(org.junit.Test)

Example 43 with UnknownHostException

use of java.net.UnknownHostException in project bazel by bazelbuild.

the class HttpConnector method connect.

URLConnection connect(URL originalUrl, ImmutableMap<String, String> requestHeaders) throws IOException {
    if (Thread.interrupted()) {
        throw new InterruptedIOException();
    }
    URL url = originalUrl;
    if (HttpUtils.isProtocol(url, "file")) {
        return url.openConnection();
    }
    List<Throwable> suppressions = new ArrayList<>();
    int retries = 0;
    int redirects = 0;
    int connectTimeout = MIN_CONNECT_TIMEOUT_MS;
    while (true) {
        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection(proxyHelper.createProxyIfNeeded(url));
            boolean isAlreadyCompressed = COMPRESSED_EXTENSIONS.contains(HttpUtils.getExtension(url.getPath())) || COMPRESSED_EXTENSIONS.contains(HttpUtils.getExtension(originalUrl.getPath()));
            for (Map.Entry<String, String> entry : requestHeaders.entrySet()) {
                if (isAlreadyCompressed && Ascii.equalsIgnoreCase(entry.getKey(), "Accept-Encoding")) {
                    // appears to be compressed.
                    continue;
                }
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.setConnectTimeout(connectTimeout);
            // The read timeout is always large because it stays in effect after this method.
            connection.setReadTimeout(READ_TIMEOUT_MS);
            // Java tries to abstract HTTP error responses for us. We don't want that. So we're going
            // to try and undo any IOException that doesn't appear to be a legitimate I/O exception.
            int code;
            try {
                connection.connect();
                code = connection.getResponseCode();
            } catch (FileNotFoundException ignored) {
                code = connection.getResponseCode();
            } catch (UnknownHostException e) {
                String message = "Unknown host: " + e.getMessage();
                eventHandler.handle(Event.progress(message));
                throw new UnrecoverableHttpException(message);
            } catch (IllegalArgumentException e) {
                // This will happen if the user does something like specify a port greater than 2^16-1.
                throw new UnrecoverableHttpException(e.getMessage());
            } catch (IOException e) {
                // message.
                if (e.getMessage() == null) {
                    throw new UnrecoverableHttpException("Failed to even get an error message from " + url);
                }
                if (!e.getMessage().startsWith("Server returned")) {
                    throw e;
                }
                code = connection.getResponseCode();
            }
            // 206 means partial content and only happens if caller specified Range. See RFC7233 § 4.1.
            if (code == 200 || code == 206) {
                return connection;
            } else if (code == 301 || code == 302 || code == 307) {
                readAllBytesAndClose(connection.getInputStream());
                if (++redirects == MAX_REDIRECTS) {
                    eventHandler.handle(Event.progress("Redirect loop detected in " + originalUrl));
                    throw new UnrecoverableHttpException("Redirect loop detected");
                }
                url = HttpUtils.getLocation(connection);
                if (code == 301) {
                    originalUrl = url;
                }
            } else if (code == 403) {
                // jart@ has noticed BitBucket + Amazon AWS downloads frequently flake with this code.
                throw new IOException(describeHttpResponse(connection));
            } else if (code == 408) {
                // that request on a new connection. Quoth RFC7231 § 6.5.7
                throw new IOException(describeHttpResponse(connection));
            } else if (// 4xx means client seems to have erred quoth RFC7231 § 6.5
            code < 500 || // Server doesn't support function quoth RFC7231 § 6.6.2
            code == 501 || // Host not configured on server cf. RFC7231 § 6.6.3
            code == 502 || code == 505) {
                // Server refuses to support version quoth RFC7231 § 6.6.6
                // This is a permanent error so we're not going to retry.
                readAllBytesAndClose(connection.getErrorStream());
                throw new UnrecoverableHttpException(describeHttpResponse(connection));
            } else {
                // However we will retry on some 5xx errors, particularly 500 and 503.
                throw new IOException(describeHttpResponse(connection));
            }
        } catch (UnrecoverableHttpException e) {
            throw e;
        } catch (IOException e) {
            if (connection != null) {
                // If we got here, it means we might not have consumed the entire payload of the
                // response, if any. So we're going to force this socket to disconnect and not be
                // reused. This is particularly important if multiple threads end up establishing
                // connections to multiple mirrors simultaneously for a large file. We don't want to
                // download that large file twice.
                connection.disconnect();
            }
            // We don't respect the Retry-After header (RFC7231 § 7.1.3) because it's rarely used and
            // tends to be too conservative when it is. We're already being good citizens by using
            // exponential backoff. Furthermore RFC law didn't use the magic word "MUST".
            int timeout = IntMath.pow(2, retries) * MIN_RETRY_DELAY_MS;
            if (e instanceof SocketTimeoutException) {
                eventHandler.handle(Event.progress("Timeout connecting to " + url));
                connectTimeout = Math.min(connectTimeout * 2, MAX_CONNECT_TIMEOUT_MS);
                // If we got connect timeout, we're already doing exponential backoff, so no point
                // in sleeping too.
                timeout = 1;
            } else if (e instanceof InterruptedIOException) {
                // Please note that SocketTimeoutException is a subtype of InterruptedIOException.
                throw e;
            }
            if (++retries == MAX_RETRIES) {
                if (!(e instanceof SocketTimeoutException)) {
                    eventHandler.handle(Event.progress(format("Error connecting to %s: %s", url, e.getMessage())));
                }
                for (Throwable suppressed : suppressions) {
                    e.addSuppressed(suppressed);
                }
                throw e;
            }
            // Java 7 allows us to create a tree of all errors that led to the ultimate failure.
            suppressions.add(e);
            eventHandler.handle(Event.progress(format("Failed to connect to %s trying again in %,dms", url, timeout)));
            url = originalUrl;
            try {
                sleeper.sleepMillis(timeout);
            } catch (InterruptedException translated) {
                throw new InterruptedIOException();
            }
        } catch (RuntimeException e) {
            if (connection != null) {
                connection.disconnect();
            }
            eventHandler.handle(Event.progress(format("Unknown error connecting to %s: %s", url, e)));
            throw e;
        }
    }
}
Also used : InterruptedIOException(java.io.InterruptedIOException) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) URL(java.net.URL) HttpURLConnection(java.net.HttpURLConnection) SocketTimeoutException(java.net.SocketTimeoutException) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 44 with UnknownHostException

use of java.net.UnknownHostException in project bigbluebutton by bigbluebutton.

the class NetworkSocketStreamSender method connect.

public void connect(String host, int port, boolean useTLS) throws ConnectionException {
    //We use this value to devie how to create the socket
    this.useTLS = useTLS;
    System.out.println("NetworkSocketStreamSender: connecting to " + host + ":" + port);
    try {
        //Handling if TLS is enabled or not
        if (useTLS) {
            System.out.println("Connecting over TLS");
            sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
            outstream = new DataOutputStream(sslSocket.getOutputStream());
        } else {
            //If not use regular socket
            socket = new Socket(host, port);
            outstream = new DataOutputStream(socket.getOutputStream());
        }
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new ConnectionException("UnknownHostException: " + host);
    } catch (IOException e) {
        e.printStackTrace();
        throw new ConnectionException("IOException: " + host + ":" + port);
    }
}
Also used : UnknownHostException(java.net.UnknownHostException) DataOutputStream(java.io.DataOutputStream) IOException(java.io.IOException) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket)

Example 45 with UnknownHostException

use of java.net.UnknownHostException in project bigbluebutton by bigbluebutton.

the class NetworkStreamSender method trySocketConnection.

private boolean trySocketConnection(String host, int port) {
    try {
        Socket socket = new Socket();
        InetSocketAddress endpoint = new InetSocketAddress(host, port);
        socket.connect(endpoint, 5000);
        socket.close();
        return true;
    } catch (UnknownHostException e) {
        System.out.println("Unknown host [" + host + "]");
    } catch (IOException e) {
        System.out.println("Cannot connect to [" + host + ":" + port + "]");
    }
    return false;
}
Also used : UnknownHostException(java.net.UnknownHostException) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) Socket(java.net.Socket)

Aggregations

UnknownHostException (java.net.UnknownHostException)884 InetAddress (java.net.InetAddress)365 IOException (java.io.IOException)246 InetSocketAddress (java.net.InetSocketAddress)91 Test (org.junit.Test)79 SocketException (java.net.SocketException)70 ArrayList (java.util.ArrayList)66 Socket (java.net.Socket)49 SocketTimeoutException (java.net.SocketTimeoutException)44 URL (java.net.URL)40 File (java.io.File)39 MalformedURLException (java.net.MalformedURLException)35 HashMap (java.util.HashMap)35 ConnectException (java.net.ConnectException)28 HttpURLConnection (java.net.HttpURLConnection)28 NetworkInterface (java.net.NetworkInterface)26 Properties (java.util.Properties)26 Inet4Address (java.net.Inet4Address)24 URI (java.net.URI)24 InputStream (java.io.InputStream)23