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:xanthanov.droid.funrun.PlaceSearcher.java

public List<GooglePlace> getNearbyPlaces(String search, LatLng currentLocation, int radiusMeters)
        throws UnknownHostException, GmapException, JSONException, MalformedURLException,
        java.io.UnsupportedEncodingException {
    URL url = null;/*  w  ww  .j  ava2s.  c  om*/
    HttpURLConnection conn = null;
    String urlString = null;
    CharSequence queryStr = stringToQuery.get(search);
    if (queryStr == null) {//If we didn't get a fixed category, must have been passed a custom search string, so search by name. 
        queryStr = "name=" + java.net.URLEncoder.encode(search.toString(), "UTF-8");
        System.out.println("Custom query string: " + queryStr);
    }

    try {
        urlString = mapsApiUrl + "?" + buildLocationString(currentLocation) + "&radius=" + radiusMeters + "&"
                + queryStr + "&sensor=true" + "&key=" + apiKey;

        url = new URL(urlString);

        conn = (HttpURLConnection) url.openConnection();

        return parseJsonResult(new BufferedReader(new InputStreamReader(conn.getInputStream())));
    } catch (MalformedURLException e) {
        throw new MalformedURLException(
                "Invalid URL: " + urlString + "\nPlease check your internet connection and try again.");
    } catch (UnknownHostException e) {
        throw new UnknownHostException(
                "Unable to connect to Google Maps.\nPlease check your internet connection and try again.");
    } catch (JSONException e) {
        throw new JSONException(
                "Failure parsing place info retreived from Google Maps.\nPlease try again later.");
    } catch (IOException e) {
        throw new JSONException(
                "Error downloading info from Google Maps.\nPlease check your internet connection and try again.");
    } catch (GmapException e) {
        throw new GmapException(e.getMessage() + "\nPlease check your internet connection and try again.");
    } finally {
        if (conn != null)
            conn.disconnect();
    }

}

From source file:org.getlantern.firetweet.util.net.FiretweetHostAddressResolver.java

private InetAddress[] resolveInternal(String originalHost, String host) throws IOException {
    if (isValidIpAddress(host))
        return fromAddressString(originalHost, host);
    // First, I'll try to load address cached.
    if (mHostCache.containsKey(host)) {
        final InetAddress[] hostAddr = mHostCache.get(host);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got cached " + Arrays.toString(hostAddr));
        }//  ww  w  .  j  a  va2s  .co m
        return hostAddr;
    }
    // Then I'll try to load from custom host mapping.
    // Stupid way to find top domain, but really fast.
    if (mHostMapping.contains(host)) {
        final String mappedAddr = mHostMapping.getString(host, null);
        if (mappedAddr != null) {
            final InetAddress[] hostAddr = fromAddressString(originalHost, mappedAddr);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Got mapped " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
    }
    mSystemHosts.reloadIfNeeded();
    if (mSystemHosts.contains(host)) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, mSystemHosts.getAddress(host));
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got hosts " + Arrays.toString(hostAddr));
        }
        return hostAddr;
    }
    final String customMappedHost = findHost(host);
    if (customMappedHost != null) {
        final InetAddress[] hostAddr = fromAddressString(originalHost, customMappedHost);
        mHostCache.put(originalHost, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got mapped address " + customMappedHost + " for host " + host);
        }
        return hostAddr;
    }
    // Use TCP DNS Query if enabled.
    final Resolver dns = getResolver();
    if (dns != null && mPreferences.getBoolean(KEY_TCP_DNS_QUERY, false)) {
        final Lookup lookup = new Lookup(new Name(host), Type.A, DClass.IN);
        final Record[] records;
        lookup.setResolver(dns);
        lookup.run();
        final int result = lookup.getResult();
        if (result != Lookup.SUCCESSFUL) {
            throw new UnknownHostException("Unable to resolve " + host + ", " + lookup.getErrorString());
        }
        records = lookup.getAnswers();
        final ArrayList<InetAddress> resolvedAddresses = new ArrayList<>();
        // Test each IP address resolved.
        for (final Record record : records) {
            if (record instanceof ARecord) {
                final InetAddress ipv4Addr = ((ARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress()));
            } else if (record instanceof AAAARecord) {
                final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
                resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress()));
            }
        }
        if (!resolvedAddresses.isEmpty()) {
            final InetAddress[] hostAddr = resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
            mHostCache.put(originalHost, hostAddr);
            if (Utils.isDebugBuild()) {
                Log.d(RESOLVER_LOGTAG, "Resolved " + Arrays.toString(hostAddr));
            }
            return hostAddr;
        }
        // No address is reachable, but I believe the IP is correct.

        for (final Record record : records) {
            if (record instanceof CNAMERecord)
                return resolveInternal(originalHost, ((CNAMERecord) record).getTarget().toString());
        }
    }
    if (Utils.isDebugBuild()) {
        Log.w(RESOLVER_LOGTAG, "Resolve address " + host + " failed, using original host");
    }
    final InetAddress[] defaultAddresses = InetAddress.getAllByName(host);
    mHostCache.put(host, defaultAddresses);
    return defaultAddresses;
}

From source file:org.apache.jmeter.protocol.http.control.DNSCacheManager.java

/**
 * Sends DNS request via system or custom DNS resolver
 *///from  ww w.j  a va 2  s.c  om
private InetAddress[] requestLookup(String host) throws UnknownHostException {
    InetAddress[] addresses = null;
    if (isCustomResolver() && ((ExtendedResolver) resolver).getResolvers().length > 0) {
        try {
            Lookup lookup = new Lookup(host, Type.A);
            lookup.setCache(lookupCache);
            if (timeoutMs > 0) {
                resolver.setTimeout(timeoutMs / 1000, timeoutMs % 1000);
            }
            lookup.setResolver(resolver);
            Record[] records = lookup.run();
            if (records == null || records.length == 0) {
                throw new UnknownHostException("Failed to resolve host name: " + host);
            }
            addresses = new InetAddress[records.length];
            for (int i = 0; i < records.length; i++) {
                addresses[i] = ((ARecord) records[i]).getAddress();
            }
        } catch (TextParseException tpe) {
            log.debug("Failed to create Lookup object: " + tpe);
        }
    } else {
        addresses = systemDefaultDnsResolver.resolve(host);
        if (log.isDebugEnabled()) {
            log.debug("Cache miss: " + host + " Thread #" + JMeterContextService.getContext().getThreadNum()
                    + ", resolved with system resolver into " + Arrays.toString(addresses));
        }
    }
    return addresses;
}

From source file:jnode.vm.NetAPIImpl.java

/**
 * Gets the default local address./*from   ww w .  j  av  a  2 s .  c  om*/
 * 
 * @return InetAddress
 */

public InetAddress getLocalAddress() throws UnknownHostException {
    for (Device dev : devManager.getDevicesByAPI(NetDeviceAPI.class)) {
        try {
            final NetDeviceAPI api = (NetDeviceAPI) dev.getAPI(NetDeviceAPI.class);
            log.info("getLocalAddress: " + dev.toString());
            final ProtocolAddressInfo addrInfo = api.getProtocolAddressInfo(EthernetConstants.ETH_P_IP);
            log.info("getLocalAddress: addrInfo " + addrInfo.toString());
            if (addrInfo != null) {
                final ProtocolAddress addr = addrInfo.getDefaultAddress();
                if (addr != null) {
                    log.info("getLocalAddress(" + (addr.toInetAddress()).toString() + ")");
                    //return addr.toInetAddress();
                }
            }
        } catch (ApiNotFoundException ex) {
            // Strange, but ignore
        }
    }

    throw new UnknownHostException("No configured address found");
}

From source file:org.cloudata.core.common.ipc.CServer.java

/**
 * A convience method to bind to a given address and report 
 * better exceptions if the address is not a valid host.
 * @param socket the socket to bind// w w w  . j a  va 2s .c om
 * @param address the address to bind to
 * @param backlog the number of connections allowed in the queue
 * @throws BindException if the address can't be bound
 * @throws UnknownHostException if the address isn't a valid host name
 * @throws IOException other random errors from bind
 */
static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException {
    try {
        socket.bind(address, backlog);
    } catch (BindException e) {
        throw new BindException("Problem binding to " + address + "," + e.getMessage());
    } catch (SocketException e) {
        // If they try to bind to a different host's address, give a better
        // error message.
        if ("Unresolved address".equals(e.getMessage())) {
            throw new UnknownHostException("Invalid hostname for server: " + address.getHostName());
        } else {
            throw e;
        }
    }
}

From source file:com.taobao.adfs.distributed.rpc.Server.java

/**
 * A convenience method to bind to a given address and report better exceptions if the address is not a valid host.
 * /*from  ww  w  . j av a 2  s.c  om*/
 * @param socket
 *          the socket to bind
 * @param address
 *          the address to bind to
 * @param backlog
 *          the number of connections allowed in the queue
 * @throws BindException
 *           if the address can't be bound
 * @throws UnknownHostException
 *           if the address isn't a valid host name
 * @throws IOException
 *           other random errors from bind
 */
public static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException {
    try {
        socket.bind(address, backlog);
    } catch (BindException e) {
        BindException bindException = new BindException(
                "Problem binding to " + address + " : " + e.getMessage());
        bindException.initCause(e);
        throw bindException;
    } catch (SocketException e) {
        // If they try to bind to a different host's address, give a better
        // error message.
        if ("Unresolved address".equals(e.getMessage())) {
            throw new UnknownHostException("Invalid hostname for server: " + address.getHostName());
        } else {
            throw e;
        }
    }
}

From source file:io.joynr.util.JoynrUtil.java

public static void checkConnectivity(String host) throws IOException {
    InetAddress headUnitAddr = InetAddress.getByName(host);
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    NetworkInterface iface;//from ww w  .  ja  va  2  s  . co  m

    while (interfaces.hasMoreElements()) {
        iface = interfaces.nextElement();
        if (headUnitAddr.isReachable(iface, 0, 5000)) {
            return;
        }
    }
    throw new UnknownHostException("Connectivity check to the host \"" + host + "\" has failed");
}

From source file:de.pawlidi.openaletheia.utils.AletheiaUtils.java

/**
 * //from   w  ww. j  a  v a 2 s. c o  m
 * @return
 * @throws UnknownHostException
 */
public static InetAddress getLocalIpAddress() throws UnknownHostException {
    try {
        InetAddress localAddress = null;
        // load all existed network interfaces
        for (Enumeration<?> networkInterfaces = NetworkInterface.getNetworkInterfaces(); networkInterfaces
                .hasMoreElements();) {
            NetworkInterface networkInterface = (NetworkInterface) networkInterfaces.nextElement();

            for (Enumeration<?> ipAddresses = networkInterface.getInetAddresses(); ipAddresses
                    .hasMoreElements();) {
                InetAddress ipAddress = (InetAddress) ipAddresses.nextElement();
                if (!ipAddress.isLoopbackAddress()) {
                    if (ipAddress.isSiteLocalAddress()) {
                        return ipAddress;
                    } else if (localAddress == null) {
                        localAddress = ipAddress;
                    }
                }
            }
        }
        if (localAddress != null) {
            return localAddress;
        }
        // try to get localhost address
        localAddress = InetAddress.getLocalHost();
        if (localAddress == null) {
            throw new UnknownHostException("Could not load localhost ip address");
        }
        return localAddress;
    } catch (Exception e) {
        UnknownHostException unknownHostException = new UnknownHostException(
                "Could not load localhost ip address " + e);
        unknownHostException.initCause(e);
        throw unknownHostException;
    }
}

From source file:IntergrationTest.OCSPIntegrationTest.java

private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception {
    InputStream is = null;/*from  ww w.  j  av a 2 s  .  c o m*/
    InputStream is_temp = null;
    try {
        if (uri == null)
            return null;
        URL url = uri.toURL();
        if (bActiveCheckUnknownHost) {
            url.getProtocol();
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1)
                port = url.getDefaultPort();
            InetSocketAddress isa = new InetSocketAddress(host, port);
            if (isa.isUnresolved()) {
                //fix JNLP popup error issue
                throw new UnknownHostException("Host Unknown:" + isa.toString());
            }

        }
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);
        uc.setInstanceFollowRedirects(true);
        setTimeout(uc);
        String contentEncoding = uc.getContentEncoding();
        int len = uc.getContentLength();
        // is = uc.getInputStream();
        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) {
            is_temp = uc.getInputStream();
            is = new GZIPInputStream(is_temp);

        } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) {
            is_temp = uc.getInputStream();
            is = new InflaterInputStream(is_temp);

        } else {
            is = uc.getInputStream();

        }
        if (len != -1) {
            int ch, i = 0;
            byte[] res = new byte[len];
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);

            }
            return res;

        } else {
            ArrayList<byte[]> buffer = new ArrayList<>();
            int buf_len = 1024;
            byte[] res = new byte[buf_len];
            int ch, i = 0;
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);
                if (i == buf_len) {
                    //rotate
                    buffer.add(res);
                    i = 0;
                    res = new byte[buf_len];

                }

            }
            int total_len = buffer.size() * buf_len + i;
            byte[] buf = new byte[total_len];
            for (int j = 0; j < buffer.size(); j++) {
                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }
            if (i > 0) {
                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }
            return buf;

        }

    } catch (Exception e) {
        e.printStackTrace();
        return null;

    } finally {
        closeInputStream(is_temp);
        closeInputStream(is);

    }

}

From source file:org.mariotaku.twidere.util.net.TwidereDns.java

private InetAddress[] fromResolver(String originalHost, String host, int depth) throws IOException {
    final Resolver dns = getResolver();
    final Lookup lookup = new Lookup(new Name(host), Type.A, DClass.IN);
    final Record[] records;
    lookup.setResolver(dns);// www. j av  a 2 s.co m
    lookup.run();
    final int result = lookup.getResult();
    if (result != Lookup.SUCCESSFUL) {
        throw new UnknownHostException("Unable to resolve " + host + ", " + lookup.getErrorString());
    }
    records = lookup.getAnswers();
    final ArrayList<InetAddress> resolvedAddresses = new ArrayList<>();
    // Test each IP address resolved.
    long ttl = -1;
    for (final Record record : records) {
        if (ttl == -1) {
            ttl = record.getTTL();
        }
        if (record instanceof ARecord) {
            final InetAddress ipv4Addr = ((ARecord) record).getAddress();
            resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv4Addr.getAddress()));
        } else if (record instanceof AAAARecord) {
            final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
            resolvedAddresses.add(InetAddress.getByAddress(originalHost, ipv6Addr.getAddress()));
        }
    }
    if (!resolvedAddresses.isEmpty()) {
        final InetAddress[] hostAddr = resolvedAddresses.toArray(new InetAddress[resolvedAddresses.size()]);
        putCache(originalHost, hostAddr, ttl, TimeUnit.SECONDS);
        if (BuildConfig.DEBUG) {
            Log.v(RESOLVER_LOGTAG, "Resolved " + Arrays.toString(hostAddr));
        }
        return hostAddr;
    }
    // No address is reachable, but I believe the IP is correct.

    for (final Record record : records) {
        if (record instanceof CNAMERecord)
            return resolveInternal(originalHost, ((CNAMERecord) record).getTarget().toString(), depth + 1);
    }
    return null;
}