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:org.apache.http.HC4.impl.conn.InMemoryDnsResolver.java

/**
 * {@inheritDoc}//from   w  w  w. j  a va2 s . com
 */
@Override
public InetAddress[] resolve(final String host) throws UnknownHostException {
    final InetAddress[] resolvedAddresses = dnsMap.get(host);
    if (log.isInfoEnabled()) {
        log.info("Resolving " + host + " to " + Arrays.deepToString(resolvedAddresses));
    }
    if (resolvedAddresses == null) {
        throw new UnknownHostException(host + " cannot be resolved");
    }
    return resolvedAddresses;
}

From source file:com.epam.reportportal.apache.http.impl.conn.InMemoryDnsResolver.java

/**
 * {@inheritDoc}//from ww w. ja  va  2 s. c  o m
 */
public InetAddress[] resolve(final String host) throws UnknownHostException {
    final InetAddress[] resolvedAddresses = dnsMap.get(host);
    if (log.isInfoEnabled()) {
        log.info("Resolving " + host + " to " + Arrays.deepToString(resolvedAddresses));
    }
    if (resolvedAddresses == null) {
        throw new UnknownHostException(host + " cannot be resolved");
    }
    return resolvedAddresses;
}

From source file:org.apache.http2.impl.conn.InMemoryDnsResolver.java

/**
 * {@inheritDoc}//www.  jav a2s.c om
 */
public InetAddress[] resolve(String host) throws UnknownHostException {
    InetAddress[] resolvedAddresses = dnsMap.get(host);
    if (log.isInfoEnabled()) {
        log.info("Resolving " + host + " to " + Arrays.deepToString(resolvedAddresses));
    }
    if (resolvedAddresses == null) {
        throw new UnknownHostException(host + " cannot be resolved");
    }
    return resolvedAddresses;
}

From source file:org.apache.hadoop.hbase.ipc.RpcConnection.java

protected RpcConnection(Configuration conf, HashedWheelTimer timeoutTimer, ConnectionId remoteId,
        String clusterId, boolean isSecurityEnabled, Codec codec, CompressionCodec compressor)
        throws IOException {
    if (remoteId.getAddress().isUnresolved()) {
        throw new UnknownHostException("unknown host: " + remoteId.getAddress().getHostName());
    }/*  w  ww  . j a  va2  s . c  om*/
    this.timeoutTimer = timeoutTimer;
    this.codec = codec;
    this.compressor = compressor;

    UserGroupInformation ticket = remoteId.getTicket().getUGI();
    SecurityInfo securityInfo = SecurityInfo.getInfo(remoteId.getServiceName());
    this.useSasl = isSecurityEnabled;
    Token<? extends TokenIdentifier> token = null;
    String serverPrincipal = null;
    if (useSasl && securityInfo != null) {
        AuthenticationProtos.TokenIdentifier.Kind tokenKind = securityInfo.getTokenKind();
        if (tokenKind != null) {
            TokenSelector<? extends TokenIdentifier> tokenSelector = AbstractRpcClient.TOKEN_HANDLERS
                    .get(tokenKind);
            if (tokenSelector != null) {
                token = tokenSelector.selectToken(new Text(clusterId), ticket.getTokens());
            } else if (LOG.isDebugEnabled()) {
                LOG.debug("No token selector found for type " + tokenKind);
            }
        }
        String serverKey = securityInfo.getServerPrincipal();
        if (serverKey == null) {
            throw new IOException("Can't obtain server Kerberos config key from SecurityInfo");
        }
        serverPrincipal = SecurityUtil.getServerPrincipal(conf.get(serverKey),
                remoteId.address.getAddress().getCanonicalHostName().toLowerCase());
        if (LOG.isDebugEnabled()) {
            LOG.debug("RPC Server Kerberos principal name for service=" + remoteId.getServiceName() + " is "
                    + serverPrincipal);
        }
    }
    this.token = token;
    this.serverPrincipal = serverPrincipal;
    if (!useSasl) {
        authMethod = AuthMethod.SIMPLE;
    } else if (token != null) {
        authMethod = AuthMethod.DIGEST;
    } else {
        authMethod = AuthMethod.KERBEROS;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Use " + authMethod + " authentication for service " + remoteId.serviceName + ", sasl="
                + useSasl);
    }
    reloginMaxBackoff = conf.getInt("hbase.security.relogin.maxbackoff", 5000);
    this.remoteId = remoteId;
}

From source file:com.cloupia.feature.nimble.http.MySSLSocketFactory.java

public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
        throws IOException, UnknownHostException {

    TrustManager[] trustAllCerts = getTrustManager();

    try {//from   w w  w.  ja  va 2 s  . c  om

        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        SocketFactory socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        return socketFactory.createSocket(host, port, clientHost, clientPort);

    }

    catch (Exception ex) {

        throw new UnknownHostException("Problems to connect " + host + ex.toString());

    }

}

From source file:com.eventsourcing.hlc.NTPServerTimeProvider.java

/**
 * Creates NTPServerTimeProvider with a custom list of NTP server addresses
 *
 * @param ntpServers Array of custom NTP server addresses
 * @throws UnknownHostException Throws UnknownHostException for the first unresolved host, if no hosts were resolvable
 *///from  www .j  av  a  2 s. c  o m
public NTPServerTimeProvider(String[] ntpServers) throws UnknownHostException, SocketException {
    client = new NTPUDPClient();
    setServers(ntpServers);
    if (servers.isEmpty()) {
        throw new UnknownHostException(ntpServers[0]);
    }
    setSocketTimeout();
}

From source file:com.lfv.yada.net.client.ClientNetworkManager.java

public ClientNetworkManager(int terminalId, ClientBundle bundle, SocketAddress serverSocketAddr,
        SocketAddress localhostBindSocketAddr, SocketAddress multicastSocketAddr, int multicastTTL,
        TerminalProperties properties) throws IOException {

    // Create a logger for this class
    log = LogFactory.getLog(getClass());

    // Load terminal properties
    this.properties = properties;

    // Setup stuff
    this.terminalId = terminalId;
    this.bundle = bundle;
    this.serverSocketAddr = new SocketAddress(serverSocketAddr);

    // Resolve local host address
    InetAddress localHost = getLocalHostFix();
    if (localHost == null) {
        localHost = InetAddress.getLocalHost();
        if (localHost == null)
            throw new UnknownHostException("Could not resolve ip address of localhost");
    }/* w w w. java  2  s  . co m*/

    // The socket to be used for sending and receiving unicast packets
    DatagramSocket usocket;
    if (localhostBindSocketAddr.getAddress() == 0)
        usocket = new DatagramSocket();
    else
        usocket = new DatagramSocket(localhostBindSocketAddr.getPort(),
                localhostBindSocketAddr.getInetAddress());

    // The multicast socket
    InetAddress maddr = multicastSocketAddr.getInetAddress();
    int mport = multicastSocketAddr.getPort();
    MulticastSocket msocket = null;

    multicastAvailable = (maddr != null && mport > 0);
    if (multicastAvailable) {
        msocket = new MulticastSocket(mport);
        try {
            msocket.joinGroup(maddr);
            msocket.setTimeToLive(multicastTTL);
        } catch (SocketException ex) {
            log.warn("!!!");
            log.warn("!!! Unable to create multicast socket! Multicasting has been disabled!");
            log.warn("!!! On linux systems a default gateway must be defined, try:");
            log.warn("!!! > route add default gw <some_ip_address>");
            log.warn("!!!");
            msocket = null;
            multicastAvailable = false;
        }
    } else
        log.warn("No multicast address or port defined, multicasting has been disabled!");

    // Store the local unicast ip address and port
    localSocketAddr = new SocketAddress(localHost, usocket.getLocalPort());

    // Create a receiver and a sender (send/recv must use the same port number)
    receiver = new ClientPacketReceiver(terminalId, usocket, msocket);
    sender = new ClientPacketSender(usocket, msocket, multicastSocketAddr);

    // Create a transaction mananger
    transactionManager = new TransactionManager(sender);
    receiver.setControlPacketDispatcher(transactionManager);
    receiver.setSendPacketDispatcher(sender);

    // Create a timer for handling pings
    timer = new Timer("Snetworkmanager", true);

    // Initialize packet pool
    PacketPool.getPool();

    // Setup request handlers
    transactionManager.setRequestHandler(Packet.SESSION, new SessionRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.UPDATE, new UpdateRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INFO, new InfoRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.ISA, new IsaRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.CONNECT, new ConnectRequestPacketHandler());
    transactionManager.setRequestHandler(Packet.INITIATE, new InitiateRequestPacketHandler());
}

From source file:org.jnode.net.ipv4.resolver.ResolverImpl.java

/**
 * Gets the address(es) of the given hostname.
 * /*from  w  w  w .j ava 2s. c  om*/
 * @param hostname
 * @return All addresses of the given hostname. The returned array is at
 *         least 1 address long.
 * @throws java.net.UnknownHostException
 */
public ProtocolAddress[] getByName(final String hostname) throws UnknownHostException {
    if (hostname == null) {
        throw new UnknownHostException("null");
    }
    if (hostname.equals("*")) {
        // FIXME ... why is this a special case? Comment please or fix it.
        throw new UnknownHostException("*");
    }
    ProtocolAddress[] protocolAddresses = getFromHostsFile(hostname);
    if (protocolAddresses != null) {
        return protocolAddresses;
    }
    throw new UnknownHostException(hostname);
}

From source file:bixo.operations.ProcessRobotsTask.java

@Override
public void run() {
    _flowProcess.increment(FetchCounters.DOMAINS_PROCESSING, 1);

    try {// w  w  w  .  j a va2  s .c o  m
        DomainInfo domainInfo = new DomainInfo(_protocolAndDomain);
        if (!domainInfo.isValidHostAddress()) {
            throw new UnknownHostException(_protocolAndDomain);
        }

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(String.format("Resolved %s to %s", _protocolAndDomain, domainInfo.getHostAddress()));
        }

        String domain = domainInfo.getDomain();
        String pld = DomainNames.getPLD(domain);
        if (!_scorer.isGoodDomain(domain, pld)) {
            _flowProcess.increment(FetchCounters.DOMAINS_SKIPPED, 1);
            _flowProcess.increment(FetchCounters.URLS_SKIPPED, _urls.size());

            LOGGER.debug("Skipping URLs from not-good domain: " + domain);

            emptyQueue(_urls, GroupingKey.SKIPPED_GROUPING_KEY, _collector, _flowProcess);
        } else {
            BaseRobotRules robotRules = getRobotRules(_fetcher, _parser,
                    new URL(domainInfo.getProtocolAndDomain() + "/robots.txt"));

            String validKey = null;
            boolean isDeferred = robotRules.isDeferVisits();
            if (isDeferred) {
                LOGGER.debug("Deferring visits to URLs from " + domainInfo.getDomain());
                _flowProcess.increment(FetchCounters.DOMAINS_DEFERRED, 1);
            } else {
                validKey = GroupingKey.makeGroupingKey(domainInfo.getHostAddress(), robotRules.getCrawlDelay());
                _flowProcess.increment(FetchCounters.DOMAINS_FINISHED, 1);
            }

            // Use the same key for every URL from this domain
            GroupedUrlDatum datum;
            while ((datum = _urls.poll()) != null) {
                ScoredUrlDatum scoreUrl;
                FetchCounters counter;
                String url = datum.getUrl();

                if (isDeferred) {
                    counter = FetchCounters.URLS_DEFERRED;
                    scoreUrl = new ScoredUrlDatum(url, GroupingKey.DEFERRED_GROUPING_KEY,
                            UrlStatus.SKIPPED_DEFERRED, 0.0);
                } else if (!robotRules.isAllowed(url)) {
                    counter = FetchCounters.URLS_BLOCKED;
                    scoreUrl = new ScoredUrlDatum(url, GroupingKey.BLOCKED_GROUPING_KEY,
                            UrlStatus.SKIPPED_BLOCKED, 0.0);
                } else {
                    double score = _scorer.generateScore(domain, pld, datum);
                    if (score == BaseScoreGenerator.SKIP_SCORE) {
                        counter = FetchCounters.URLS_SKIPPED;
                        scoreUrl = new ScoredUrlDatum(url, GroupingKey.SKIPPED_GROUPING_KEY,
                                UrlStatus.UNFETCHED, score);
                    } else {
                        counter = FetchCounters.URLS_ACCEPTED;
                        scoreUrl = new ScoredUrlDatum(url, validKey, UrlStatus.UNFETCHED, score);
                    }
                }

                scoreUrl.setPayload(datum.getPayload());
                _flowProcess.increment(counter, 1);

                // collectors aren't thread safe
                synchronized (_collector) {
                    _collector.add(BixoPlatform.clone(scoreUrl.getTuple(), _flowProcess));
                }
            }
        }
    } catch (UnknownHostException e) {
        LOGGER.debug("Unknown host: " + _protocolAndDomain);
        _flowProcess.increment(FetchCounters.DOMAINS_REJECTED, 1);
        _flowProcess.increment(FetchCounters.URLS_REJECTED, _urls.size());
        emptyQueue(_urls, GroupingKey.UNKNOWN_HOST_GROUPING_KEY, _collector, _flowProcess);
    } catch (MalformedURLException e) {
        LOGGER.debug("Invalid URL: " + _protocolAndDomain);
        _flowProcess.increment(FetchCounters.DOMAINS_REJECTED, 1);
        _flowProcess.increment(FetchCounters.URLS_REJECTED, _urls.size());
        emptyQueue(_urls, GroupingKey.INVALID_URL_GROUPING_KEY, _collector, _flowProcess);
    } catch (URISyntaxException e) {
        LOGGER.debug("Invalid URI: " + _protocolAndDomain);
        _flowProcess.increment(FetchCounters.DOMAINS_REJECTED, 1);
        _flowProcess.increment(FetchCounters.URLS_REJECTED, _urls.size());
        emptyQueue(_urls, GroupingKey.INVALID_URL_GROUPING_KEY, _collector, _flowProcess);
    } catch (Exception e) {
        LOGGER.warn("Exception processing " + _protocolAndDomain, e);
        _flowProcess.increment(FetchCounters.DOMAINS_REJECTED, 1);
        _flowProcess.increment(FetchCounters.URLS_REJECTED, _urls.size());
        emptyQueue(_urls, GroupingKey.INVALID_URL_GROUPING_KEY, _collector, _flowProcess);
    } finally {
        _flowProcess.decrement(FetchCounters.DOMAINS_PROCESSING, 1);
    }
}

From source file:com.evilisn.DAO.CertMapper.java

public static byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception

{

    InputStream is = null;/* ww  w . ja va  2s  .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 = 0, 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<byte[]>();

            int buf_len = 1024;

            byte[] res = new byte[buf_len];

            int ch = 0, 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);

    }

}