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.symbian.driver.core.controller.tasks.TEFTask.java

/**
 * @param aVisitor/*from   w ww  .j a v a2s  . co m*/
 * @param aTestExecuteScript
 * @param lExecuteOnDevice
 * @param aTask
 * @return The last execption raised when running UCC.
 * @throws JStatException
 */
private boolean runUCC(List<String> aArgs, Task aTask) {
    boolean lReturn = true;
    Socket lUccSocket = null;
    DataOutputStream lSocketOut = null;
    DataInputStream lSocketIn = null;
    int lRunNumber = 0;
    int lUccPort = -1;
    String lUccAddress = null;
    IDeviceComms.ISymbianProcess lProcess = null;

    try {
        String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":");
        lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER);

        lUccAddress = lUccSplit[0];
        lUccPort = Integer.parseInt(lUccSplit[1]);
    } catch (ParseException lParseException) {
        LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException);
        iExceptions.put(lParseException, ESeverity.ERROR);
        lReturn = false;
    } catch (NumberFormatException lNumberFormatException) {
        LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException);
        iExceptions.put(lNumberFormatException, ESeverity.ERROR);
        lReturn = false;
    }

    if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) {
        iExceptions.put(
                new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"),
                ESeverity.ERROR);
        return false;
    }

    // Run the test
    try {
        LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort);

        lUccSocket = new Socket(lUccAddress, lUccPort);
        lSocketOut = new DataOutputStream(lUccSocket.getOutputStream());
        lSocketIn = new DataInputStream(lUccSocket.getInputStream());

        LOGGER.fine("Starting UCC while still polling");
        lProcess = iDeviceProxy.createSymbianProcess();
        if (lProcess != null) {
            // run and don't wait
            if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) {
                iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR);
                lReturn = false;
            }

            // Tell UCC that the test has started.
            LOGGER.fine("Writing to UCC socket: " + lRunNumber);
            lSocketOut.writeInt(lRunNumber);
            lSocketOut.flush();

            int lUCCReply = lSocketIn.readInt();
            LOGGER.fine("UCC Reply: " + lUCCReply);
        }

    } catch (UnknownHostException lUnknownHostException) {
        LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException);
        iExceptions.put(lUnknownHostException, ESeverity.ERROR);
        return false;
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE,
                "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null
                        ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: "
                                + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:"
                                + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound()
                        : "\nUcc Socket is NULL"),
                lIOException);
        iExceptions.put(lIOException, ESeverity.ERROR);
        return false;
    } finally {

        // Close UCC
        if (lSocketOut != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket Out.");
                lUccSocket.shutdownInput();
                lUccSocket.shutdownOutput();
                lSocketOut.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lSocketIn != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket In.");
                lSocketIn.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lUccSocket != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket UCC.");
                lUccSocket.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }

        if (!lUccSocket.isClosed()) {
            LOGGER.warning("Could not close the UCC sockets properly.");
        }

        lSocketOut = null;
        lSocketIn = null;
        lUccSocket = null;

        // Poll TEF Test
        if (!lProcess.join()) {
            iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR);
            lReturn = false;
        }

    }
    return lReturn;
}

From source file:com.app.mvc.http.ext.StrictSSLProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket a <code>SSLSocket</code> value
 * @throws 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.
 * @throws UnknownHostException       If we are not able to resolve
 *                                    the SSL sessions returned server host name.
 *//*from   ww  w .  j a va2  s  . c o  m*/
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 (logger.isDebugEnabled()) {
        logger.debug("Server certificate chain:");
        for (int i = 0; i < certs.length; i++) {
            logger.debug("X509Certificate[" + i + "]=" + certs[i]);
        }
    }
    //get the common name from the first cert
    String cn = getCN(dn);
    if (hostname.equalsIgnoreCase(cn)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Target hostname valid: " + cn);
        }
    } else {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cn + "'");
    }
}

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

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

    try {//w w  w.  j  a  v a 2s. c om
        InetAddress ip = InetAddress.getLocalHost();
        byte[] macAddress = NetworkInterface.getByInetAddress(ip).getHardwareAddress();

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

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

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

        // NODE_LENGTH = 6
        else if (macAddress.length > SnowCrystal.NODE_LENGTH && macAddress.length != 8) {
            throw new UnknownHostException("Unknown host address type");
        }
    }

    catch (Exception e) {
        e.printStackTrace();
        new Random().nextBytes(address);
    }

    return address;
}

From source file:org.apache.hadoop.security.SecurityUtil.java

/**
 * Construct the service key for a token
 * @param addr InetSocketAddress of remote connection with a token
 * @return "ip:port" or "host:port" depending on the value of
 *          hadoop.security.token.service.use_ip
 *//* ww w .j a  v a 2  s  . c o m*/
public static Text buildTokenService(InetSocketAddress addr) {
    String host = null;
    if (useIpForTokenService) {
        if (addr.isUnresolved()) { // host has no ip address
            throw new IllegalArgumentException(new UnknownHostException(addr.getHostName()));
        }
        host = addr.getAddress().getHostAddress();
    } else {
        host = addr.getHostName().toLowerCase();
    }
    return new Text(host + ":" + addr.getPort());
}

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

/**
 * Construct the service key for a token
 *
 * @param addr InetSocketAddress of remote connection with a token
 *
 * @return "ip:port" or "host:port" depending on the value of hadoop.security.token.service.use_ip
 *//*  w w w  .ja  v a2s. c o m*/
public static Text buildTokenService(InetSocketAddress addr) {
    String host = null;
    if (useIpForTokenService) {
        if (addr.isUnresolved()) { // host has no ip address
            throw new IllegalArgumentException(new UnknownHostException(addr.getHostName()));
        }
        host = addr.getAddress().getHostAddress();
    } else {
        host = StringUtils.toLowerCase(addr.getHostName());
    }
    return new Text(host + ":" + addr.getPort());
}

From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 *
 * @param socket/*from   w  w  w .ja  v a2 s.  com*/
 *            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 {
    synchronized (this) {
        if (!verifyHostname)
            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 = (X509Certificate[]) session.getPeerCertificates();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    X500Principal subjectDN = certs[0].getSubjectX500Principal();

    // get the common names from the first cert
    List<String> cns = getCNs(subjectDN);
    boolean foundHostName = false;
    for (String cn : cns) {
        if (hostname.equalsIgnoreCase(cn)) {
            foundHostName = true;
            break;
        }
    }
    if (!foundHostName) {
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cns + "'");
    }
}

From source file:org.jsslutils.extra.apachehttpclient.SslContextedSecureProtocolSocketFactory.java

/**
 * Describe <code>verifyHostname</code> method here.
 * //from   w  w w . j a va  2s. com
 * @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.
 * @throws CertificateParsingException
 */
private void verifyHostname(SSLSocket socket) throws IOException, UnknownHostException {
    synchronized (this) {
        if (!verifyHostname)
            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 = (X509Certificate[]) session.getPeerCertificates();
    if (certs == null || certs.length == 0)
        throw new SSLPeerUnverifiedException("No server certificates found!");

    try {
        List<String> cns = new ArrayList<String>();
        boolean foundDnsSan = false;
        Collection<List<?>> subjectAltNames = certs[0].getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            for (List<?> san : subjectAltNames) {
                if (((Integer) san.get(0)).intValue() == 2) {
                    foundDnsSan = true;
                    String sanDns = (String) san.get(1);
                    cns.add(sanDns);
                    if (hostname.equalsIgnoreCase(sanDns)) {
                        return;
                    }
                }
            }
        }
        if (!foundDnsSan) {
            // get the common names from the first cert
            X500Principal subjectDN = certs[0].getSubjectX500Principal();
            cns = getCNs(subjectDN);
            for (String cn : cns) {
                if (hostname.equalsIgnoreCase(cn)) {
                    return;
                }
            }
        }
        throw new SSLPeerUnverifiedException(
                "HTTPS hostname invalid: expected '" + hostname + "', received '" + cns + "'");
    } catch (CertificateParsingException e) {
        throw new IOException(e);
    }
}

From source file:us.paulevans.basicxslt.Utils.java

/**
 * Method to determine if inputted xml file is valid and well-formed.
 * @param saXmlFile/*ww w. j  a v  a 2  s . c om*/
 * @throws Exception If saXmlFile is invalid or not well-formed.
 */
public void isValidXml(FileContent faXmlFile, boolean aCheckWarning, boolean aCheckError,
        boolean aCheckFatalError) throws SAXNotSupportedException, SAXNotRecognizedException,
        ParserConfigurationException, SAXException, IOException {

    SAXParserFactory factory;

    checkWarning = aCheckWarning;
    checkError = aCheckError;
    checkFatalError = aCheckFatalError;
    factory = SAXParserFactory.newInstance();
    factory.setValidating(true);
    factory.setNamespaceAware(true);
    try {
        factory.setFeature(VALIDATION_FEATURE, true);
        factory.setFeature(SCHEMA_FEATURE, true);
        SAXParser parser = factory.newSAXParser();
        parser.parse(faXmlFile.getInputStream(), this);
    } catch (UnknownHostException aException) {
        // log and re-throw runtime exception...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw new UnknownHostException(stringFactory.getString(LabelStringFactory.ERRORS_NETWORK_CONNECT));
    } catch (SocketException aException) {
        // log and re-throw runtime exception...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw new SocketException(stringFactory.getString(LabelStringFactory.ERRORS_NETWORK_CONNECT));
    } catch (SAXNotSupportedException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (SAXNotRecognizedException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (ParserConfigurationException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (SAXException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    } catch (IOException aException) {
        // log and re-throw...
        logger.error(ExceptionUtils.getFullStackTrace(aException));
        throw aException;
    }
}

From source file:com.groupon.odo.bmp.http.BrowserMobHostNameResolver.java

@Override
public InetAddress resolve(String hostname) throws IOException {
    // BEGIN ODO CHANGES
    // send requests to Odo
    hostname = "127.0.0.1";
    // END ODO CHANGES

    String remapping = remappings.get(hostname);
    if (remapping != null) {
        hostname = remapping;/*from ww  w. j  a v  a 2s.c om*/
    }

    try {
        return Address.getByAddress(hostname);
    } catch (UnknownHostException e) {
        // that's fine, this just means it's not an IP address and we gotta look it up, which is common
    }

    boolean isCached = this.isCached(hostname);

    Lookup lookup = new Lookup(Name.fromString(hostname), Type.A);
    lookup.setCache(cache);
    lookup.setResolver(resolver);

    Date start = new Date();
    Record[] records = lookup.run();
    Date end = new Date();

    if (records == null || records.length == 0) {
        throw new UnknownHostException(hostname);
    }

    // assembly the addr object
    ARecord a = (ARecord) records[0];
    InetAddress addr = InetAddress.getByAddress(hostname, a.getAddress().getAddress());

    if (!isCached) {
        // TODO: Associate the the host name with the connection. We do this because when using persistent
        // connections there won't be a lookup on the 2nd, 3rd, etc requests, and as such we wouldn't be able to
        // know what IP address we were requesting.
        RequestInfo.get().dns(start, end, addr.getHostAddress());
    } else {
        // if it is a cached hit, we just record zero since we don't want
        // to skew the data with method call timings (specially under load)
        RequestInfo.get().dns(end, end, addr.getHostAddress());
    }

    return addr;
}

From source file:com.petalmd.armor.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  ww  w.ja  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.ARMOR_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.ARMOR_HTTP_XFORWARDEDFOR_TRUSTEDPROXIES);

        final boolean xForwardedEnforce = settings
                .getAsBoolean(ConfigConstants.ARMOR_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);
    }

}