Example usage for java.net UnknownHostException UnknownHostException

List of usage examples for java.net UnknownHostException UnknownHostException

Introduction

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

Prototype

public UnknownHostException(String message) 

Source Link

Document

Constructs a new UnknownHostException with the specified detail message.

Usage

From source file:com.floragunn.searchguard.util.SecurityUtil.java

public static InetAddress getProxyResolvedHostAddressFromRequest(final RestRequest request,
        final Settings settings) throws UnknownHostException {

    // this.logger.debug(request.getClass().toString());

    final String oaddr = ((InetSocketAddress) request.getRemoteAddress()).getHostString();
    // this.logger.debug("original hostname: " + addr);

    String raddr = oaddr;/*from  w w w.j  a  v a 2  s. c  o m*/

    if (oaddr == null || oaddr.isEmpty()) {
        throw new UnknownHostException("Original host is <null> or <empty>");
    }

    final InetAddress iaddr = InetAddress.getByName(oaddr);

    final String xForwardedForHeader = settings.get(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_HEADER,
            "X-Forwarded-For");

    if (xForwardedForHeader != null && !xForwardedForHeader.isEmpty()) {

        final String xForwardedForValue = request.header(xForwardedForHeader);

        //logger.trace("xForwardedForHeader is " + xForwardedForHeader + ":" + xForwardedForValue);

        final String[] xForwardedTrustedProxies = settings
                .getAsArray(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_TRUSTEDPROXIES);

        final boolean xForwardedEnforce = settings
                .getAsBoolean(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_ENFORCE, false);

        if (xForwardedForValue != null && !xForwardedForValue.isEmpty()) {
            final List<String> addresses = Arrays.asList(xForwardedForValue.replace(" ", "").split(","));
            final List<String> proxiesPassed = new ArrayList<String>(addresses.subList(1, addresses.size()));

            if (xForwardedTrustedProxies.length == 0) {
                throw new UnknownHostException("No trusted proxies");
            }

            proxiesPassed.removeAll(Arrays.asList(xForwardedTrustedProxies));

            //logger.debug(proxiesPassed.size() + "/" + proxiesPassed);

            if (proxiesPassed.size() == 0
                    && (Arrays.asList(xForwardedTrustedProxies).contains(oaddr) || iaddr.isLoopbackAddress())) {

                raddr = addresses.get(0).trim();

            } else {
                throw new UnknownHostException("Not all proxies are trusted");
            }

        } else {
            if (xForwardedEnforce) {
                throw new UnknownHostException("Forward header enforced but not present");
            }
        }

    }

    if (raddr == null || raddr.isEmpty()) {
        throw new UnknownHostException("Host is <null> or <empty>");
    }

    if (raddr.equals(oaddr)) {
        return iaddr;
    } else {
        // if null or "" then loopback is returned
        return InetAddress.getByName(raddr);
    }

}

From source file:org.codice.ddf.spatial.kml.endpoint.KmlEndpoint.java

private UriBuilder generateEndpointUrl(String path, UriBuilder uriBuilder) throws UnknownHostException {
    UriBuilder builder = uriBuilder;/*  w  w w .j  a v  a 2  s.  co  m*/
    builder.host(SystemBaseUrl.getHost());

    try {
        builder.port(Integer.parseInt(SystemBaseUrl.getPort()));
    } catch (NumberFormatException nfe) {
        LOGGER.debug(
                "Cannot convert the current DDF port: {} to an integer." + " Defaulting to port in invocation.",
                SystemBaseUrl.getPort());
        throw new UnknownHostException("Unable to determine port DDF is using.");
    }

    builder = builder.replacePath(path);

    return builder;
}

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @exception SSLPeerUnverifiedException  If there are problems obtaining
 * the server certificates from the SSL session, or the server host name 
 * does not match with the "Common Name" in the server certificates 
 * SubjectDN.//from w  ww  .j  a  va2s . c o m
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
protected void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    if (session == null) {
        throw new UnknownHostException("could not obtain session from socket");
    }
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        String msg = "Could not resolve SSL sessions server hostname: " + hostname;
        // Under WebSphere, hostname can be equal to proxy-hostname
        log.warn(msg, uhe);
        //         throw new UnknownHostException(msg);
    }

    javax.security.cert.X509Certificate[] certs = session.getPeerCertificateChain();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    //get the servers DN in its string representation
    String dn = certs[0].getSubjectDN().getName();

    //might be useful to print out all certificates we receive from the
    //server, in case one has to debug a problem with the installed certs.
    if (log.isInfoEnabled()) {
        log.info("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            log.info("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (log.isInfoEnabled()) {
            log.info("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:org.exjello.mail.ExchangeConnection.java

public static ExchangeConnection createConnection(String protocol, Session session, String host, int port,
        String username, String password) throws Exception {
    String prefix = "mail." + protocol.toLowerCase() + ".";
    boolean debugPassword = Boolean.parseBoolean(session.getProperty(DEBUG_PASSWORD_PROPERTY));
    String pwd = (password == null) ? null : debugPassword ? password : "<password>";
    if (host == null || username == null || password == null) {
        if (session.getDebug()) {
            session.getDebugOut().println("Missing parameter; host=\"" + host + "\",username=\"" + username
                    + "\",password=\"" + pwd + "\"");
        }/*  w w  w .j  a va 2s  .  c o m*/
        throw new IllegalStateException("Host, username, and password must be specified.");
    }
    boolean unfiltered = Boolean.parseBoolean(session.getProperty(UNFILTERED_PROPERTY));
    /* Mirco */
    String filterLastCheck = session.getProperty(ExchangeConstants.FILTER_LAST_CHECK);
    String filterFrom = session.getProperty(ExchangeConstants.FILTER_FROM_PROPERTY);
    String filterNotFrom = session.getProperty(ExchangeConstants.FILTER_NOT_FROM_PROPERTY);
    String filterTo = session.getProperty(ExchangeConstants.FILTER_TO_PROPERTY);
    boolean delete = Boolean.parseBoolean(session.getProperty(DELETE_PROPERTY));
    boolean secure = Boolean.parseBoolean(session.getProperty(prefix + SSL_PROPERTY));
    int limit = -1;
    String limitString = session.getProperty(LIMIT_PROPERTY);
    if (limitString != null) {
        try {
            limit = Integer.parseInt(limitString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid limit specified: " + limitString);
        }
    }
    try {
        URL url = new URL(host);
        // if parsing succeeded, then strip out the components and use
        secure = "https".equalsIgnoreCase(url.getProtocol());
        host = url.getHost();
        int specifiedPort = url.getPort();
        if (specifiedPort != -1)
            port = specifiedPort;
    } catch (MalformedURLException ex) {
        if (session.getDebug()) {
            session.getDebugOut().println("Not parsing " + host + " as a URL; using explicit options for "
                    + "secure, host, and port.");
        }
    }
    if (port == -1) {
        try {
            port = Integer.parseInt(session.getProperty(prefix + PORT_PROPERTY));
        } catch (Exception ignore) {
        }
        if (port == -1)
            port = secure ? HTTPS_PORT : HTTP_PORT;
    }
    String server = (secure ? "https://" : "http://") + host;
    if (secure ? (port != HTTPS_PORT) : (port != HTTP_PORT)) {
        server += ":" + port;
    }
    String mailbox = session.getProperty(MAILBOX_PROPERTY);
    if (mailbox == null) {
        mailbox = session.getProperty(prefix + FROM_PROPERTY);
        if (mailbox == null) {
            mailbox = InternetAddress.getLocalAddress(session).getAddress();
        }
    }

    int index = username.indexOf(':');
    if (index != -1) {
        mailbox = username.substring(index + 1);
        username = username.substring(0, index);
        String mailboxOptions = null;
        index = mailbox.indexOf('[');
        if (index != -1) {
            mailboxOptions = mailbox.substring(index + 1);
            mailboxOptions = mailboxOptions.substring(0, mailboxOptions.indexOf(']'));
            mailbox = mailbox.substring(0, index);
        }
        if (mailboxOptions != null) {
            Properties props = null;
            try {
                props = parseOptions(mailboxOptions);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Unable to parse mailbox options: " + ex.getMessage(), ex);
            }
            String value = props.getProperty("unfiltered");
            if (value != null)
                unfiltered = Boolean.parseBoolean(value);

            /* Mirco */
            value = props.getProperty("filterLastCheck");
            if (value != null)
                filterLastCheck = value;
            value = props.getProperty("filterTo");
            if (value != null)
                filterTo = value;
            value = props.getProperty("filterFrom");
            if (value != null)
                filterFrom = value;
            value = props.getProperty("filterNotFrom");
            if (value != null)
                filterNotFrom = value;

            value = props.getProperty("delete");
            if (value != null)
                delete = Boolean.parseBoolean(value);
            value = props.getProperty("limit");
            if (value != null) {
                try {
                    limit = Integer.parseInt(value);
                } catch (NumberFormatException ex) {
                    throw new NumberFormatException("Invalid limit specified: " + value);
                }
            }
        } else if (session.getDebug()) {
            session.getDebugOut().println(
                    "No mailbox options specified; " + "using explicit limit, unfiltered, and delete.");
        }
    } else if (session.getDebug()) {
        session.getDebugOut().println("No mailbox specified in username; "
                + "using explicit mailbox, limit, unfiltered, and delete.");
    }
    int timeout = -1;
    String timeoutString = session.getProperty(prefix + TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            timeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid timeout value: " + timeoutString);
        }
    }
    int connectionTimeout = -1;
    timeoutString = session.getProperty(prefix + CONNECTION_TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            connectionTimeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid connection timeout value: " + timeoutString);
        }
    }
    InetAddress localAddress = null;
    String localAddressString = session.getProperty(prefix + LOCAL_ADDRESS_PROPERTY);
    if (localAddressString != null) {
        try {
            localAddress = InetAddress.getByName(localAddressString);
        } catch (Exception ex) {
            throw new UnknownHostException("Invalid local address specified: " + localAddressString);
        }
    }
    if (mailbox == null) {
        throw new IllegalStateException("No mailbox specified.");
    }
    if (session.getDebug()) {
        PrintStream debugStream = session.getDebugOut();
        debugStream.println("Server:\t" + server);
        debugStream.println("Username:\t" + username);
        debugStream.println("Password:\t" + pwd);
        debugStream.println("Mailbox:\t" + mailbox);
        debugStream.print("Options:\t");
        debugStream.print((limit > 0) ? "Message Limit = " + limit : "Unlimited Messages");
        debugStream.print(unfiltered ? "; Unfiltered" : "; Filtered to Unread");
        debugStream.print(filterLastCheck == null || "".equals(filterLastCheck) ? "; NO filterLastCheck"
                : "; Filtered after " + filterLastCheck);
        debugStream.print(filterFrom == null || "".equals(filterFrom) ? "; NO filterFromDomain"
                : "; Filtered from " + filterFrom);
        debugStream.print(filterNotFrom == null || "".equals(filterNotFrom) ? "; NO filterNotFrom"
                : "; Filtered not from " + filterNotFrom);
        debugStream.print(
                filterTo == null || "".equals(filterTo) ? "; NO filterToEmail" : "; Filtered to " + filterTo);
        debugStream.println(delete ? "; Delete Messages on Delete" : "; Mark as Read on Delete");
        if (timeout > 0) {
            debugStream.println("Read timeout:\t" + timeout + " ms");
        }
        if (connectionTimeout > 0) {
            debugStream.println("Connection timeout:\t" + connectionTimeout + " ms");
        }
    }
    return new ExchangeConnection(session, server, mailbox, username, password, timeout, connectionTimeout,
            localAddress, unfiltered, delete, limit, filterLastCheck, filterFrom, filterNotFrom, filterTo);
}

From source file:org.exjello.mail.Exchange2003Connection.java

public static Exchange2003Connection createConnection(String protocol, Session session, String host, int port,
        String username, String password) throws Exception {
    String prefix = "mail." + protocol.toLowerCase() + ".";
    boolean debugPassword = Boolean.parseBoolean(session.getProperty(DEBUG_PASSWORD_PROPERTY));
    String pwd = (password == null) ? null : debugPassword ? password : "<password>";
    if (host == null || username == null || password == null) {
        if (session.getDebug()) {
            session.getDebugOut().println("Missing parameter; host=\"" + host + "\",username=\"" + username
                    + "\",password=\"" + pwd + "\"");
        }//from   w  w w.  j  a  va2s.c o  m
        throw new IllegalStateException("Host, username, and password must be specified.");
    }
    boolean unfiltered = Boolean.parseBoolean(session.getProperty(UNFILTERED_PROPERTY));
    /* Mirco */
    String filterLastCheck = session.getProperty(ExchangeConstants.FILTER_LAST_CHECK);
    String filterFrom = session.getProperty(ExchangeConstants.FILTER_FROM_PROPERTY);
    String filterNotFrom = session.getProperty(ExchangeConstants.FILTER_NOT_FROM_PROPERTY);
    String filterTo = session.getProperty(ExchangeConstants.FILTER_TO_PROPERTY);
    boolean delete = Boolean.parseBoolean(session.getProperty(DELETE_PROPERTY));
    boolean secure = Boolean.parseBoolean(session.getProperty(prefix + SSL_PROPERTY));
    int limit = -1;
    String limitString = session.getProperty(LIMIT_PROPERTY);
    if (limitString != null) {
        try {
            limit = Integer.parseInt(limitString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid limit specified: " + limitString);
        }
    }
    try {
        URL url = new URL(host);
        // if parsing succeeded, then strip out the components and use
        secure = "https".equalsIgnoreCase(url.getProtocol());
        host = url.getHost();
        int specifiedPort = url.getPort();
        if (specifiedPort != -1)
            port = specifiedPort;
    } catch (MalformedURLException ex) {
        if (session.getDebug()) {
            session.getDebugOut().println("Not parsing " + host + " as a URL; using explicit options for "
                    + "secure, host, and port.");
        }
    }
    if (port == -1) {
        try {
            port = Integer.parseInt(session.getProperty(prefix + PORT_PROPERTY));
        } catch (Exception ignore) {
        }
        if (port == -1)
            port = secure ? HTTPS_PORT : HTTP_PORT;
    }
    String server = (secure ? "https://" : "http://") + host;
    if (secure ? (port != HTTPS_PORT) : (port != HTTP_PORT)) {
        server += ":" + port;
    }
    String mailbox = session.getProperty(MAILBOX_PROPERTY);
    if (mailbox == null) {
        mailbox = session.getProperty(prefix + FROM_PROPERTY);
        if (mailbox == null) {
            mailbox = InternetAddress.getLocalAddress(session).getAddress();
        }
    }

    int index = username.indexOf(':');
    if (index != -1) {
        mailbox = username.substring(index + 1);
        username = username.substring(0, index);
        String mailboxOptions = null;
        index = mailbox.indexOf('[');
        if (index != -1) {
            mailboxOptions = mailbox.substring(index + 1);
            mailboxOptions = mailboxOptions.substring(0, mailboxOptions.indexOf(']'));
            mailbox = mailbox.substring(0, index);
        }
        if (mailboxOptions != null) {
            Properties props = null;
            try {
                props = parseOptions(mailboxOptions);
            } catch (Exception ex) {
                throw new IllegalArgumentException("Unable to parse mailbox options: " + ex.getMessage(), ex);
            }
            String value = props.getProperty("unfiltered");
            if (value != null)
                unfiltered = Boolean.parseBoolean(value);

            /* Mirco */
            value = props.getProperty("filterLastCheck");
            if (value != null)
                filterLastCheck = value;
            value = props.getProperty("filterTo");
            if (value != null)
                filterTo = value;
            value = props.getProperty("filterFrom");
            if (value != null)
                filterFrom = value;
            value = props.getProperty("filterNotFrom");
            if (value != null)
                filterNotFrom = value;

            value = props.getProperty("delete");
            if (value != null)
                delete = Boolean.parseBoolean(value);
            value = props.getProperty("limit");
            if (value != null) {
                try {
                    limit = Integer.parseInt(value);
                } catch (NumberFormatException ex) {
                    throw new NumberFormatException("Invalid limit specified: " + value);
                }
            }
        } else if (session.getDebug()) {
            session.getDebugOut().println(
                    "No mailbox options specified; " + "using explicit limit, unfiltered, and delete.");
        }
    } else if (session.getDebug()) {
        session.getDebugOut().println("No mailbox specified in username; "
                + "using explicit mailbox, limit, unfiltered, and delete.");
    }
    int timeout = -1;
    String timeoutString = session.getProperty(prefix + TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            timeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid timeout value: " + timeoutString);
        }
    }
    int connectionTimeout = -1;
    timeoutString = session.getProperty(prefix + CONNECTION_TIMEOUT_PROPERTY);
    if (timeoutString != null) {
        try {
            connectionTimeout = Integer.parseInt(timeoutString);
        } catch (NumberFormatException ex) {
            throw new NumberFormatException("Invalid connection timeout value: " + timeoutString);
        }
    }
    InetAddress localAddress = null;
    String localAddressString = session.getProperty(prefix + LOCAL_ADDRESS_PROPERTY);
    if (localAddressString != null) {
        try {
            localAddress = InetAddress.getByName(localAddressString);
        } catch (Exception ex) {
            throw new UnknownHostException("Invalid local address specified: " + localAddressString);
        }
    }
    if (mailbox == null) {
        throw new IllegalStateException("No mailbox specified.");
    }
    if (session.getDebug()) {
        PrintStream debugStream = session.getDebugOut();
        debugStream.println("Server:\t" + server);
        debugStream.println("Username:\t" + username);
        debugStream.println("Password:\t" + pwd);
        debugStream.println("Mailbox:\t" + mailbox);
        debugStream.print("Options:\t");
        debugStream.print((limit > 0) ? "Message Limit = " + limit : "Unlimited Messages");
        debugStream.print(unfiltered ? "; Unfiltered" : "; Filtered to Unread");
        debugStream.print(filterLastCheck == null || "".equals(filterLastCheck) ? "; NO filterLastCheck"
                : "; Filtered after " + filterLastCheck);
        debugStream.print(filterFrom == null || "".equals(filterFrom) ? "; NO filterFromDomain"
                : "; Filtered from " + filterFrom);
        debugStream.print(filterNotFrom == null || "".equals(filterNotFrom) ? "; NO filterNotFrom"
                : "; Filtered not from " + filterNotFrom);
        debugStream.print(
                filterTo == null || "".equals(filterTo) ? "; NO filterToEmail" : "; Filtered to " + filterTo);
        debugStream.println(delete ? "; Delete Messages on Delete" : "; Mark as Read on Delete");
        if (timeout > 0) {
            debugStream.println("Read timeout:\t" + timeout + " ms");
        }
        if (connectionTimeout > 0) {
            debugStream.println("Connection timeout:\t" + connectionTimeout + " ms");
        }
    }
    return new Exchange2003Connection(session, server, mailbox, username, password, timeout, connectionTimeout,
            localAddress, unfiltered, delete, limit, filterLastCheck, filterFrom, filterNotFrom, filterTo);
}

From source file:org.cloudgraph.hbase.mapreduce.GraphInputFormat.java

/**
 * Uses {@link InetAddress} in case of {@link DNS} lookup failure.
 * /* w  ww . j a v a 2  s . co m*/
 * @param ipAddr
 *          the address
 * @return the reverse address
 * @throws NamingException
 * @throws UnknownHostException
 */
public String reverseDNS(InetAddress ipAddr) throws NamingException, UnknownHostException {
    String hostName = this.reverseDNSCache.get(ipAddr);
    if (hostName == null) {
        String ipAddressString = null;
        try {
            ipAddressString = DNS.reverseDns(ipAddr, null);
        } catch (Exception e) {
            ipAddressString = InetAddress.getByName(ipAddr.getHostAddress()).getHostName();
        }
        if (ipAddressString == null)
            throw new UnknownHostException("No host found for " + ipAddr);
        hostName = Strings.domainNamePointerToHostName(ipAddressString);
        this.reverseDNSCache.put(ipAddr, hostName);
    }
    return hostName;
}

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

/**
 * Returns all the IPs associated with the provided interface, if any, as
 * a list of InetAddress objects./*from   www .j  a v a2 s  .c  o m*/
 *
 * @param strInterface
 *            The name of the network interface or sub-interface to query
 *            (eg eth0 or eth0:0) or the string "default"
 * @param returnSubinterfaces
 *            Whether to return IPs associated with subinterfaces of
 *            the given interface
 * @return A list of all the IPs associated with the provided
 *         interface. The local host IP is returned if the interface
 *         name "default" is specified or there is an I/O error looking
 *         for the given interface.
 * @throws UnknownHostException
 *             If the given interface is invalid
 *
 */
public static List<InetAddress> getIPsAsInetAddressList(String strInterface, boolean returnSubinterfaces)
        throws UnknownHostException {
    if ("default".equals(strInterface)) {
        return Arrays.asList(InetAddress.getByName(cachedHostAddress));
    }
    NetworkInterface netIf;
    try {
        netIf = NetworkInterface.getByName(strInterface);
        if (netIf == null) {
            netIf = getSubinterface(strInterface);
        }
    } catch (SocketException e) {
        LOG.warn("I/O error finding interface " + strInterface + ": " + e.getMessage());
        return Arrays.asList(InetAddress.getByName(cachedHostAddress));
    }
    if (netIf == null) {
        throw new UnknownHostException("No such interface " + strInterface);
    }

    // NB: Using a LinkedHashSet to preserve the order for callers
    // that depend on a particular element being 1st in the array.
    // For example, getDefaultIP always returns the first element.
    LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>();
    allAddrs.addAll(Collections.list(netIf.getInetAddresses()));
    if (!returnSubinterfaces) {
        allAddrs.removeAll(getSubinterfaceInetAddrs(netIf));
    }
    return new Vector<InetAddress>(allAddrs);
}

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

/**
 * Performs a sanity check on the list of hostnames/IPs to verify they at least
 * appear to be valid./*from  w  w  w.  ja  v  a 2 s. c o m*/
 * @param names - List of hostnames/IPs
 * @throws UnknownHostException
 */
public static void verifyHostnames(String[] names) throws UnknownHostException {
    for (String name : names) {
        if (name == null) {
            throw new UnknownHostException("null hostname found");
        }
        // The first check supports URL formats (e.g. hdfs://, etc.). 
        // java.net.URI requires a schema, so we add a dummy one if it doesn't
        // have one already.
        URI uri = null;
        try {
            uri = new URI(name);
            if (uri.getHost() == null) {
                uri = new URI("http://" + name);
            }
        } catch (URISyntaxException e) {
            uri = null;
        }
        if (uri == null || uri.getHost() == null) {
            throw new UnknownHostException(name + " is not a valid Inet address");
        }
    }
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Performs a sanity check on the list of hostnames/IPs to verify they at least appear to be valid.
 *
 * @param names - List of hostnames/IPs/*from   w  w w. j a  va  2 s  .  com*/
 *
 * @throws UnknownHostException
 */
public static void verifyHostnames(String[] names) throws UnknownHostException {
    for (String name : names) {
        if (name == null) {
            throw new UnknownHostException("null hostname found");
        }
        // The first check supports URL formats (e.g. hdfs://, etc.).
        // java.net.URI requires a schema, so we add a dummy one if it doesn't
        // have one already.
        URI uri = null;
        try {
            uri = new URI(name);
            if (uri.getHost() == null) {
                uri = new URI("http://" + name);
            }
        } catch (URISyntaxException e) {
            uri = null;
        }
        if (uri == null || uri.getHost() == null) {
            throw new UnknownHostException(name + " is not a valid Inet address");
        }
    }
}

From source file:org.apache.bookkeeper.bookie.Bookie.java

/**
 * Return the configured address of the bookie.
 *///from ww w  . j a v a2  s  .c om
public static BookieSocketAddress getBookieAddress(ServerConfiguration conf) throws UnknownHostException {
    String iface = conf.getListeningInterface();
    if (iface == null) {
        iface = "default";
    }
    InetSocketAddress inetAddr = new InetSocketAddress(DNS.getDefaultHost(iface), conf.getBookiePort());
    String hostAddress = inetAddr.getAddress().getHostAddress();
    if (conf.getUseHostNameAsBookieID()) {
        hostAddress = inetAddr.getAddress().getCanonicalHostName();
    }
    BookieSocketAddress addr = new BookieSocketAddress(hostAddress, conf.getBookiePort());
    if (addr.getSocketAddress().getAddress().isLoopbackAddress() && !conf.getAllowLoopback()) {
        throw new UnknownHostException("Trying to listen on loopback address, " + addr
                + " but this is forbidden by default " + "(see ServerConfiguration#getAllowLoopback())");
    }
    return addr;
}