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.magnum.dataup.VideoController.java

private static InetAddress getLocalHostLANAddress() throws UnknownHostException {
    try {//from  w ww.  j a  va 2  s.c  om
        InetAddress candidateAddress = null;
        // Iterate all NICs (network interface cards)...
        for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) {
            NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
            // Iterate all IP addresses assigned to each card...
            for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) {
                InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
                if (!inetAddr.isLoopbackAddress()) {

                    if (inetAddr.isSiteLocalAddress()) {
                        // Found non-loopback site-local address. Return it immediately...
                        return inetAddr;
                    } else if (candidateAddress == null) {
                        // Found non-loopback address, but not necessarily site-local.
                        // Store it as a candidate to be returned if site-local address is not subsequently found...
                        candidateAddress = inetAddr;
                        // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates,
                        // only the first. For subsequent iterations, candidate will be non-null.
                    }
                }
            }
        }
        if (candidateAddress != null) {
            // We did not find a site-local address, but we found some other non-loopback address.
            // Server might have a non-site-local address assigned to its NIC (or it might be running
            // IPv6 which deprecates the "site-local" concept).
            // Return this non-loopback candidate address...
            return candidateAddress;
        }
        // At this point, we did not find a non-loopback address.
        // Fall back to returning whatever InetAddress.getLocalHost() returns...
        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress == null) {
            throw new UnknownHostException(
                    "The JDK InetAddress.getLocalHost() method unexpectedly returned null.");
        }
        return jdkSuppliedAddress;
    } catch (Exception e) {
        UnknownHostException unknownHostException = new UnknownHostException(
                "Failed to determine LAN address: " + e);
        unknownHostException.initCause(e);
        throw unknownHostException;
    }
}

From source file:com.joyent.manta.http.ApacheHttpGetResponseEntityContentContinuatorTest.java

@Test(expectedExceptions = UnknownHostException.class, expectedExceptionsMessageRegExp = ".*custom fatal exception yo.*")
public void rethrowsFatalExceptions() throws Exception {
    final MantaApacheHttpClientContext connCtx = mock(MantaApacheHttpClientContext.class);
    when(connCtx.getHttpClient()).thenReturn(mock(CloseableHttpClient.class));
    final HttpGet request = new HttpGet();
    final HttpResponse response = prepareResponseWithHeaders(unmodifiableMap(ETAG,
            singleValueHeaderList(ETAG, "a"), CONTENT_LENGTH, singleValueHeaderList(CONTENT_LENGTH, "1")));
    when(response.getStatusLine())/*from  www. j  a  v  a  2  s  . co  m*/
            .thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, SC_PARTIAL_CONTENT, ""));

    final HttpDownloadContinuationMarker marker = HttpDownloadContinuationMarker.validateInitialExchange(
            extractDownloadRequestFingerprint(request), SC_OK,
            extractDownloadResponseFingerprint(response, true));

    new ApacheHttpGetResponseEntityContentContinuator(connCtx, request, marker, INFINITE_CONTINUATIONS)
            .buildContinuation(new UnknownHostException("custom fatal exception yo"), 0);
}

From source file:org.saadahmed.snowcrystal.SnowCrystal.java

public static byte[] getIpAddress() {
    byte[] address = new byte[NODE_LENGTH];

    try {//from ww  w  . j ava2  s  . c o  m
        byte[] ipAddress = InetAddress.getLocalHost().getAddress();

        // NODE_LENGTH = 6
        if (ipAddress.length < SnowCrystal.NODE_LENGTH) {
            System.arraycopy(ipAddress, 0, address, 0, ipAddress.length);
            return address;
        }

        // NODE_LENGTH = 6
        else if (ipAddress.length == SnowCrystal.NODE_LENGTH) {
            return ipAddress;
        }

        // NODE_LENGTH = 6
        else if (ipAddress.length > SnowCrystal.NODE_LENGTH && ipAddress.length == 8) {
            System.arraycopy(ipAddress, 0, address, 0, SnowCrystal.NODE_LENGTH / 2);
            System.arraycopy(ipAddress, (SnowCrystal.NODE_LENGTH / 2) + 2, address,
                    (SnowCrystal.NODE_LENGTH / 2), SnowCrystal.NODE_LENGTH / 2);
            return address;
        }

        // NODE_LENGTH = 6
        else if (ipAddress.length > SnowCrystal.NODE_LENGTH && ipAddress.length != 8) {
            throw new UnknownHostException("Unknown host address type");
        }
    } catch (Exception e) {
        e.printStackTrace();
        new SecureRandom().nextBytes(address);
    }

    return address;
}

From source file:org.apache.commons.httpclient.contrib.ssl.StrictSSLProtocolSocketFactory.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  w w.j  ava2s  .c  om
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress addr = InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    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.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.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 va  2 s  .c  o m*/
 * @exception UnknownHostException  If we are not able to resolve
 * the SSL sessions returned server host name. 
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (sslManager == null) {
        return;
    }
    ISSLErrorManager errorMng = sslManager.getSSLErrorManager();
    if (errorMng == null) {
        return;
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    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.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            java.security.cert.X509Certificate servCert = (java.security.cert.X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(certs[0].getEncoded()));
            if (!errorMng.continueErrorPeer(hostname, servCert)) {
                throw new SSLPeerUnverifiedException(
                        "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
            }
        } catch (CertificateException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        } catch (CertificateEncodingException ex) {
            LOG.error(ex.getMessage(), ex);
            throw new SSLPeerUnverifiedException(
                    "Unexpected error checking HTTPS hostname: " + ex.getMessage());
        }
    }
}

From source file:com.clican.pluto.cms.core.service.impl.IssueServiceImpl.java

private boolean issue(ISite site, ITemplate template, IDataModel dataModel, String relativePath,
        Map<ISite, FTPClient> ftpMap) {
    Template t = null;//w  w w  .  j a v  a2 s . c om
    Writer w = null;
    VelocityContext velocityContext = new VelocityContext();
    velocityContext.put("this", dataModel);
    FTPClient client = null;
    try {
        SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(template.getContent(),
                template.getName());
        t = new Template();
        t.setName(template.getName());
        t.setRuntimeServices(RuntimeSingleton.getRuntimeServices());
        t.setData(node);
        t.initDocument();
        OutputStream os = null;
        if (site.getUrl().startsWith("ftp://")) {
            client = null;
            if (ftpMap != null) {
                client = ftpMap.get(site);
            }
            if (client == null) {
                client = siteService.getFTPClient(site);
            }
            if (client == null) {
                log.error("This site[" + site.getName() + "] is unavailable");
                return false;
            }
            if (!relativePath.endsWith("/")) {
                relativePath = relativePath + "/";
            }
            client.mkd(relativePath);
            os = client.appendFileStream(relativePath + dataModel.getName() + "." + template.getSuffix());
        } else if (site.getUrl().startsWith("file://")) {
            String filePath = site.getUrl().substring(7);
            File file = new File(filePath + relativePath);
            if (file.exists()) {
                file.mkdirs();
            }
            os = new FileOutputStream(new File(file, dataModel.getName() + "." + template.getSuffix()));
        } else {
            throw new UnknownHostException(site.getUrl());
        }
        w = new OutputStreamWriter(os, "utf-8");
        t.merge(velocityContext, w);
        w.flush();
        return true;
    } catch (Exception e) {
        log.error("", e);
        return false;
    } finally {
        try {
            if (w != null) {
                w.close();
            }
        } catch (Exception e) {
            log.error("", e);
        }
        try {
            if (ftpMap == null && client != null) {
                client.logout();
                client.disconnect();
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }
}

From source file:edu.umass.cs.msocket.gns.GnsIntegration.java

/**
 * Return the GUID of the given alias//www. j  a v a  2s . co  m
 * throws UnknownHostException, so that it is similar to
 * exception thrown on DNS failure
 * @param alias
 * @param gnsCredentials
 * @return
 * @throws UnknownHostException
 */
public synchronized static String getGUIDOfAlias(String alias, GnsCredentials gnsCredentials)
        throws UnknownHostException {
    try {
        if (gnsCredentials == null) {
            long gnsCredStart = System.currentTimeMillis();
            gnsCredentials = GnsCredentials.getDefaultCredentials();
            long gnsCredEnd = System.currentTimeMillis();
            log.debug("gnsCredentials time" + (gnsCredEnd - gnsCredStart));
        }

        UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();

        long checkConnStart = System.currentTimeMillis();
        gnsClient.checkConnectivity();
        long checkConnEnd = System.currentTimeMillis();
        log.debug("checkConnectivity time" + (checkConnEnd - checkConnStart));

        long guidLookupStart = System.currentTimeMillis();
        String guidAlias = gnsClient.lookupGuid(alias);
        long guidLookupEnd = System.currentTimeMillis();
        log.debug("lookupGuid time" + (guidLookupEnd - guidLookupStart));

        return guidAlias;
    } catch (Exception ex) {
        throw new UnknownHostException(ex.toString());
    }

}

From source file:com.hortonworks.hbase.replication.bridge.HBaseServer.java

/**
 * A convenience 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//from  w  ww  . j a  v  a  2s .co  m
 * @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());
        }
        throw e;
    }
}

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

@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
    try {//from  w  w  w.  j ava2 s .  c  om
        return Arrays.asList(resolveInternal(hostname, hostname, 0));
    } catch (IOException e) {
        if (e instanceof UnknownHostException)
            throw (UnknownHostException) e;
        throw new UnknownHostException("Unable to resolve address " + e.getMessage());
    }
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 * /*from  w w w. j  a va 2  s  .  c om*/
 * @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.
 * @exception UnknownHostException
 *                If we are not able to resolve the SSL sessions returned server host name.
 */
private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    if (!verifyHostname)
        return;

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();
    try {
        // InetAddress addr = InetAddress.getByName(hostname);
        InetAddress.getByName(hostname);
    } catch (UnknownHostException uhe) {
        throw new UnknownHostException("Could not resolve SSL sessions " + "server hostname: " + hostname);
    }

    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.isDebugEnabled()) {
        LOG.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            LOG.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    // get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}