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:ch.sentric.URL.java

/**
 * Resolve the ip address from the authority.
 * //from  w ww  .j a v a 2 s. c  om
 * @return ip address as string
 * @throws UnknownHostException
 *             when ip can not be resolved
 */
public String resolveIp() throws UnknownHostException {
    final String ip = InetAddress.getByName(this.getAuthority().getAsString()).getHostAddress();
    if (ip.equals("127.0.0.1")) {
        throw new UnknownHostException("IP" + ip + "not valid");
    }
    return ip;
}

From source file:simoneb.targetprocess.TargetProcessIssueFetcher.java

@NotNull
protected InputStream getHttpFile(@NotNull String url, @NotNull IssueFetcherAuthenticator authenticator)
        throws IOException {
    LOG.debug("Performing HTTP request: \"" + url + "\"");

    URL parsedUrl = new URL(url);
    HttpClient httpClient = HttpUtil.createHttpClient(120, parsedUrl, authenticator.getCredentials(),
            authenticator.isBasicAuth()); // 2 minutes
    if (StringUtil.isEmpty(parsedUrl.getProtocol()) || StringUtil.isEmpty(parsedUrl.getHost())) {
        throw new UnknownHostException("Failed to parse the host in URL: " + url);
    }//  ww  w.j a v a  2 s .  c o  m

    GetMethod get = new GetMethod(url);
    authenticator.applyAuthScheme(get);
    get.setRequestHeader("Accept", "application/json");

    int code = httpClient.executeMethod(get);

    if (code < 200 || code >= 300) {
        handleHttpError(code, get);
    }

    LOG.debug("HTTP response: " + code + ", length: " + get.getResponseContentLength());
    InputStream stream = get.getResponseBodyAsStream();
    if (stream == null) {
        throw new ConnectionException("HTTP response is not available from \"" + url + "\"");
    }
    return stream;
}

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

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams arg4) throws IOException, UnknownHostException, ConnectTimeoutException {
    TrustManager[] trustAllCerts = getTrustManager();

    try {/*  ww  w  .  j a v a2 s. co  m*/

        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);

    }

    catch (Exception ex) {

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

    }

}

From source file:com.adito.networkplaces.store.cifs.CIFSMount.java

public FileObject createVFSFileObject(String path,
        PasswordCredentials credentials/*, DAVTransaction transaction*/)
        throws IOException, DAVAuthenticationRequiredException {

    super.getStore().getName();

    URI uri = getRootVFSURI(SystemProperties.get("jcifs.encoding", "cp860"));

    try {//from  ww w .  j a va 2 s.  c  om
        uri.setScheme("smb");
        if (credentials != null) {
            uri.setUserinfo(DAVUtilities.encodeURIUserInfo(credentials.getUsername()
                    + (credentials.getPassword() != null ? ":" + new String(credentials.getPassword()) : "")));
        }
        uri.setPath(uri.getPath() + (uri.getPath().endsWith("/") ? "" : "/")
                + DAVUtilities.encodePath(path, SystemProperties.get("jcifs.encoding", "cp860")));
        FileObject root = getStore().getRepository().getFileSystemManager().resolveFile(uri.toString());
        if (root.getType().equals(FileType.FOLDER)) {
            // Extra check so that the correct exception is thrown.
            root.getChildren();
        }
        return root;
    } catch (FileSystemException fse) {
        if (fse.getCause().getClass().getName().equals("jcifs.smb.SmbAuthException")) {
            throw new DAVAuthenticationRequiredException(getMountString());
        }
        if (fse.getCause() != null && fse.getCause() instanceof SmbException
                && ((SmbException) fse.getCause()).getRootCause() != null
                && "Connection timeout".equals(((SmbException) fse.getCause()).getRootCause().getMessage())) {
            throw new UnknownHostException(uri.getHost());
        }
        if (log.isDebugEnabled())
            log.debug("File system exception! ", fse);
        throw fse;
    }
}

From source file:com.adobe.ags.curly.controller.AuthHandler.java

private void loginTest() {
    CloseableHttpClient client = null;/*from  w w w.j a  va2s .co  m*/
    try {
        if (!model.requiredFieldsPresentProperty().get()) {
            Platform.runLater(() -> {
                model.loginConfirmedProperty().set(false);
                model.statusMessageProperty().set(ApplicationState.getMessage(INCOMPLETE_FIELDS));
            });
            return;
        }

        String url = getUrlBase() + TEST_PAGE;
        URL testUrl = new URL(url);
        InetAddress address = InetAddress.getByName(testUrl.getHost());
        if (address == null || isDnsRedirect(address)) {
            throw new UnknownHostException("Unknown host " + testUrl.getHost());
        }

        Platform.runLater(() -> {
            model.loginConfirmedProperty().set(false);
            model.statusMessageProperty().set(ApplicationState.getMessage(ATTEMPTING_CONNECTION));
        });
        client = getAuthenticatedClient();
        HttpGet loginTest = new HttpGet(url);
        HttpResponse response = client.execute(loginTest);
        StatusLine responseStatus = response.getStatusLine();

        if (responseStatus.getStatusCode() >= 200 && responseStatus.getStatusCode() < 300) {
            Platform.runLater(() -> {
                model.loginConfirmedProperty().set(true);
                model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_SUCCESSFUL));
            });
        } else {
            Platform.runLater(() -> {
                model.loginConfirmedProperty().set(false);
                model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR)
                        + responseStatus.getReasonPhrase() + " (" + responseStatus.getStatusCode() + ")");
            });
        }
    } catch (MalformedURLException | IllegalArgumentException | UnknownHostException ex) {
        Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex);
        Platform.runLater(() -> {
            model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR) + ex.getMessage());
            model.loginConfirmedProperty().set(false);
        });
    } catch (Throwable ex) {
        Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex);
        Platform.runLater(() -> {
            model.statusMessageProperty().set(ApplicationState.getMessage(CONNECTION_ERROR) + ex.getMessage());
            model.loginConfirmedProperty().set(false);
        });
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException ex) {
                Logger.getLogger(AuthHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:com.ery.ertc.estorm.util.DNS.java

/**
 * Returns all the IPs associated with the provided interface, if any, in textual form.
 * /*from   w w  w . java  2s  .c  o m*/
 * @param strInterface
 *            The name of the network interface or subinterface 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 string vector of all the IPs associated with the provided interface
 * @throws UnknownHostException
 *             If an UnknownHostException is encountered in querying the default interface or the given interface can not be found
 * 
 */
public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException {
    if ("default".equals(strInterface)) {
        return new String[] { InetAddress.getLocalHost().getHostAddress() };
    }
    NetworkInterface netIf;
    try {
        netIf = NetworkInterface.getByName(strInterface);
        if (netIf == null) {
            netIf = getSubinterface(strInterface);
            if (netIf == null) {
                throw new UnknownHostException("Unknown interface " + strInterface);
            }
        }
    } catch (SocketException e) {
        LOG.warn("Unable to get IP for interface " + strInterface, e);
        return new String[] { InetAddress.getLocalHost().getHostAddress() };
    }

    // 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));
    }

    String ips[] = new String[allAddrs.size()];
    int i = 0;
    for (InetAddress addr : allAddrs) {
        ips[i++] = addr.getHostAddress();
    }
    return ips;
}

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

/**
 * Gets the hostname of the given address.
 * //from www  . j  ava  2 s. c  om
 * @param address
 * @return All hostnames of the given hostname. The returned array is at
 *         least 1 hostname long.
 * @throws java.net.UnknownHostException
 */

public String[] getByAddress(ProtocolAddress address) throws UnknownHostException {
    String[] lookup;
    synchronized (hosts) {
        lookup = rhosts.get(address.toString());
    }
    if (lookup != null)
        return lookup;

    throw new UnknownHostException(address.toString());
}

From source file:com.qiniu.android.http.ClientConnectionOperator.java

public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local,
        final HttpContext context, final HttpParams params) throws IOException {
    if (conn == null) {
        throw new IllegalArgumentException("Connection must not be null.");
    }/*ww w  . j  a  v  a 2s .  c  o  m*/
    if (target == null) {
        throw new IllegalArgumentException("Target host must not be null.");
    }
    // local address may be null
    //@@@ is context allowed to be null?
    if (params == null) {
        throw new IllegalArgumentException("Parameters must not be null.");
    }
    if (conn.isOpen()) {
        throw new IllegalArgumentException("Connection must not be open.");
    }

    final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
    final SocketFactory sf = schm.getSocketFactory();
    String host = target.getHostName();
    String[] ips;
    if (validIP(host)) {
        ips = new String[] { host };
    } else {
        ips = systemResolv(host);
        if (ips == null || ips.length == 0) {
            throw new UnknownHostException("no ip for " + host);
        }
    }

    final int port = schm.resolvePort(target.getPort());
    for (int i = 0; i < ips.length; i++) {
        final String ip = ips[i];
        final boolean last = i == ips.length - 1;

        Socket sock = sf.createSocket();
        conn.opening(sock, target);

        try {
            Socket connsock = sf.connectSocket(sock, ip, port, local, 0, params);
            if (sock != connsock) {
                sock = connsock;
                conn.opening(sock, target);
            }
            prepareSocket(sock, context, params);
            conn.openCompleted(sf.isSecure(sock), params);
            AsyncHttpClientMod.ip.set(ip);
            return;
        } catch (ConnectException ex) {
            if (last) {
                throw new HttpHostConnectException(target, ex);
            }
        }
    }
}

From source file:com.buaa.cfs.net.DNS.java

/**
 * Returns all the IPs associated with the provided interface, if any, in textual form.
 *
 * @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 string vector 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
 *///from www  . j a v  a2 s  .co  m
public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException {
    if ("default".equals(strInterface)) {
        return new String[] { 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 new String[] { 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));
    }

    String ips[] = new String[allAddrs.size()];
    int i = 0;
    for (InetAddress addr : allAddrs) {
        ips[i++] = addr.getHostAddress();
    }
    return ips;
}

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

/**
 * Lookup the IP address(es) of an MServerSocket by its Human Readable Name
 * registered in the GNS.//from  w w  w .  ja  v  a 2  s .co m
 * throws UnknownHostException, so that it is similar to
 * exception thrown on DNS failure
 * @param name Human readable name of the MServerSocket
 * @param gnsCredentials GNS credentials to use
 * @return list of IP addresses or null if not found
 * @throws Exception
 */
public static List<InetSocketAddress> getSocketAddressFromGNS(String name, GnsCredentials gnsCredentials)
        throws UnknownHostException {
    try {
        log.trace("Retrieving IP of " + name);

        if (gnsCredentials == null) {
            gnsCredentials = GnsCredentials.getDefaultCredentials();
        }

        UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
        String guidString = gnsClient.lookupGuid(name);
        log.trace("GUID lookup " + guidString);

        JSONArray resultArray;
        // Read from the GNS
        synchronized (gnsClient) {
            resultArray = gnsClient.fieldRead(guidString, GnsConstants.SERVER_REG_ADDR, null);
        }
        Vector<InetSocketAddress> resultVector = new Vector<InetSocketAddress>();
        for (int i = 0; i < resultArray.length(); i++) {
            String str = resultArray.getString(i);
            log.trace("Value returned from GNS " + str);
            String[] Parsed = str.split(":");
            InetSocketAddress socketAddress = new InetSocketAddress(Parsed[0], Integer.parseInt(Parsed[1]));
            resultVector.add(socketAddress);
        }

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