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.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor./*from   w w w.j a  v a  2  s .co m*/
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - The timeout for the connection
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized void executeTelnetRequest(final String hostName, final int portNumber,
        final int timeout) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTelnetRequest(final String hostName, final int portNumber, final int timeout) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
    }

    Socket socket = null;

    try {
        synchronized (new Object()) {
            if (InetAddress.getByName(hostName) == null) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }
}

From source file:ch.ethz.dcg.jukefox.manager.libraryimport.AndroidAlbumCoverFetcherThread.java

private String getAlbumCoverUrlFromJukefoxServer(String urlStr) throws Exception {
    InputStream is = null;//from   w ww  .ja v a2  s  . co  m
    try {
        HttpGet httpGet = new HttpGet(urlStr);
        HttpResponse httpResp = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResp.getEntity();
        is = httpEntity.getContent();
        BufferedReader bufread = new BufferedReader(new InputStreamReader(is));
        String flag = bufread.readLine();
        if (!flag.equals("URL:")) {
            throw new UnknownHostException("Could not contact jukefox server for album image url!");
        }
        String url = bufread.readLine();

        if (!url.startsWith("http")) {
            return null;
        }

        return url;
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (Exception e) {
            Log.w(TAG, e);
        }
    }

}

From source file:org.openspaces.pu.container.servicegrid.deploy.Deploy.java

private boolean isOnGsmHost() throws UnknownHostException, RemoteException {
    InetAddress localHost = InetAddress.getLocalHost();
    InetAddress gsmHostByName = null;
    InetAddress gsmHostByAddress = null;

    try {/*from w  w w.  jav  a2 s .c o  m*/
        gsmHostByName = InetAddress.getByName(gsm.getOSDetails().getHostName());
    } catch (UnknownHostException e1) {
        try {
            gsmHostByAddress = InetAddress.getByName(gsm.getOSDetails().getHostAddress());
        } catch (UnknownHostException e2) {
            throw new UnknownHostException("failed to resolve host by name (" + gsm.getOSDetails().getHostName()
                    + ")  - caused by " + e1 + "; failed to resolve host by address ("
                    + gsm.getOSDetails().getHostAddress() + ") - caused by " + e2.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("local host: " + localHost + " GSM host-by-name: " + gsmHostByName + " host-by-address: "
                + gsmHostByAddress);
    }
    return localHost.equals(gsmHostByName) || localHost.equals(gsmHostByAddress);
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an telnet connection to a target host and port number. Silently
 * succeeds if no issues are encountered, if so, exceptions are logged and
 * re-thrown back to the requestor./* ww w .  ja va  2 s.  co  m*/
 *
 * If an exception is thrown during the <code>socket.close()</code> operation,
 * it is logged but NOT re-thrown. It's not re-thrown because it does not indicate
 * a connection failure (indeed, it means the connection succeeded) but it is
 * logged because continued failures to close the socket could result in target
 * system instability.
 * 
 * @param hostName - The target host to make the connection to
 * @param portNumber - The port number to attempt the connection on
 * @param timeout - How long to wait for a connection to establish or a response from the target
 * @param object - The serializable object to send to the target
 * @return <code>Object</code> as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeTcpRequest(final String hostName, final int portNumber,
        final int timeout, final Object object) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeTcpRequest(final String hostName, final int portNumber, final int timeout, final Object object) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug(hostName);
        DEBUGGER.debug("portNumber: {}", portNumber);
        DEBUGGER.debug("timeout: {}", timeout);
        DEBUGGER.debug("object: {}", object);
    }

    Socket socket = null;
    Object resObject = null;

    try {
        synchronized (new Object()) {
            if (StringUtils.isEmpty(InetAddress.getByName(hostName).toString())) {
                throw new UnknownHostException("No host was found in DNS for the given name: " + hostName);
            }

            InetSocketAddress socketAddress = new InetSocketAddress(hostName, portNumber);

            socket = new Socket();
            socket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(timeout));
            socket.setSoLinger(false, 0);
            socket.setKeepAlive(false);
            socket.connect(socketAddress, (int) TimeUnit.SECONDS.toMillis(timeout));

            if (!(socket.isConnected())) {
                throw new ConnectException("Failed to connect to host " + hostName + " on port " + portNumber);
            }

            ObjectOutputStream objectOut = new ObjectOutputStream(socket.getOutputStream());

            if (DEBUG) {
                DEBUGGER.debug("ObjectOutputStream: {}", objectOut);
            }

            objectOut.writeObject(object);

            resObject = new ObjectInputStream(socket.getInputStream()).readObject();

            if (DEBUG) {
                DEBUGGER.debug("resObject: {}", resObject);
            }

            PrintWriter pWriter = new PrintWriter(socket.getOutputStream(), true);

            pWriter.println(NetworkUtils.TERMINATE_TELNET + NetworkUtils.CRLF);

            pWriter.flush();
            pWriter.close();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (ClassNotFoundException cnfx) {
        throw new UtilityException(cnfx.getMessage(), cnfx);
    } finally {
        try {
            if ((socket != null) && (!(socket.isClosed()))) {
                socket.close();
            }
        } catch (IOException iox) {
            // log it - this could cause problems later on
            ERROR_RECORDER.error(iox.getMessage(), iox);
        }
    }

    return resObject;
}

From source file:com.halseyburgund.rwframework.core.RWService.java

/**
 * Handles the setting of notification texts and broadcasting intents
 * surround the calling of the action.perform() method (that does the
 * actual calling of the server)./*from ww w .  j  a va2 s  .  c  o  m*/
 * 
 * @param action to be executed
 * @return server response
 */
protected String perform(RWAction action) {
    try {
        // update last request time
        mLastRequestMsec = System.currentTimeMillis();

        try {
            setNotificationText(action.getCaption());
        } catch (Exception e) {
            Log.e(TAG, "Could not update notification text!", e);
        }

        // no point in trying when not connected
        if (!isConnected()) {
            throw new UnknownHostException("No connectivity");
        }

        // always perform actions for the current session ID
        action.setSessionId(configuration.getSessionId());

        // create an envelope ID for a file upload if the action has none yet (created in off-line mode)
        if ((action.getFilename() != null) && ("-1".equals(action.getEnvelopeId()))) {
            // create an action to create an asset envelope and perform it directly
            RWAction createEnvelopeAction = mActionFactory
                    .createCreateEnvelopeAction(action.getSelectedTagsOptions());
            String jsonResponse = createEnvelopeAction.perform(configuration.getHttpTimeOutSec());
            String envelopeKey = getString(R.string.rw_key_envelope_id);
            JSONObject jsonObj = new JSONObject(jsonResponse);
            int envelopeId = jsonObj.optInt(envelopeKey, -1);
            if (envelopeId == -1) {
                throw new UnknownHostException("Just in time creation of envelope ID for file upload failed");
            } else {
                action.setEnvelopeId(String.valueOf(envelopeId));
            }
        }

        // actually perform the action
        String result = action.perform(configuration.getHttpTimeOutSec());

        // when action is an upload a log event needs to be send now
        if (action.getFilename() != null) {
            rwSendLogEvent(R.string.rw_et_stop_upload, null, "true", true);
        }

        setNotificationText(mNotificationDefaultText);

        // broadcast operation SUCCESS intent
        broadcastActionSuccess(action, result);

        return broadcastServerMessages(result);
    } catch (UnknownHostException e) {
        String msg = "Unknown host error: " + e.getMessage();
        Log.e(TAG, msg, e);
        // broadcast operation FAILED intent
        broadcastActionFailure(action, TAG + ": " + msg, e);
        return null;
    } catch (HttpException e) {
        // expect http status code in exception message
        String msg = "HTTP error: " + e.getMessage();
        Log.e(TAG, msg, e);
        // broadcast operation FAILED intent
        // on server time out pass it as an UnknownHostException
        if (isHttpTimeOut(Integer.valueOf(e.getMessage()))) {
            broadcastActionFailure(action, TAG + ": " + msg, new UnknownHostException(msg));
        } else {
            broadcastActionFailure(action, TAG + ": " + msg, e);
        }
        return null;
    } catch (Exception e) {
        String msg = "Error: " + e.getMessage();
        Log.e(TAG, msg, e);
        // when action is an upload a log event needs to be send now
        if (action.getFilename() != null) {
            rwSendLogEvent(R.string.rw_et_stop_upload, null, "false", true);
        }
        // broadcast operation FAILED intent
        broadcastActionFailure(action, TAG + ": " + msg, e);
        return null;
    }
}

From source file:Tcpbw100.java

public void dottcp(StatusPanel sPanel) throws IOException {
    Socket ctlSocket = null;/*  w w  w.  j  av  a2 s.  c  o m*/
    if (!isApplication) {
        /*************************************************************************
         * Added by Seth Peery
         * Instead of using the getCodeBase().getHost() value for the testing server,
         * which assumes this applet is being served from the web100srv server,
         * use a parameter provided in the APPLET tag.
         * Note that for this to work the applet must be signed because you are
         * potentially accessing a server outside the source domain.
         */
        if (host == null) {
            host = getParameter("testingServer");
            System.err.println("host set to " + host);
        }
        reportHost = getParameter("reportHost");
        String reportPortString = getParameter("reportPort");
        userId = getParameter("userId");
        connectionId = getParameter("connectionId");
        /************************************************************************/
        /* fall back to the old behaviour if the APPLET tag is not set */
        if (host == null) {
            host = getCodeBase().getHost();
            System.err.println("host set to " + host);
        }
        pub_host = host;

        if (reportHost == null) {
            reportHost = host;
        }
        if (reportPortString == null) {
            reportPort = 33001;
        } else {
            reportPort = new Integer(reportPortString);
        }
    }

    results.append("web100srv: '" + host + "' [" + InetAddress.getByName(host) + "]\n");

    int ctlport = 3001;
    double wait2;
    int sbuf, rbuf;
    int i, wait, swait = 0;

    for (int iter = 0; iter < 2; iter++) {
        failed = false;
        String actual_host = host;
        try {
            if (preferIPv6.isSelected()) {
                try {
                    System.setProperty("java.net.preferIPv6Addresses", "true");
                    System.setProperty("java.net.preferIPv4Stack", "false");
                    System.err.println("java.net.preferIPv6Addresses = "
                            + System.getProperty("java.net.preferIPv6Addresses"));
                    System.err.println(
                            "java.net.preferIPv4Stack  = " + System.getProperty("java.net.preferIPv4Stack"));
                } catch (SecurityException e) {
                    System.err.println("Couldn't set system property. Check your security settings.");
                }
            }

            //this disables the checkbox while measuring
            preferIPv6.setEnabled(false);

            //preferIPv6Addresses does not seem to do anything . 
            //So I'll try a different approach
            if (preferIPv6.isSelected()) {
                outerloop: for (InetAddress addr : InetAddress.getAllByName(host)) {
                    System.err.println(host + " resolves to " + addr.getHostAddress());
                    if (addr instanceof Inet6Address) {
                        actual_host = addr.getHostAddress();
                        System.err.println("host set to IPv6 address:" + actual_host);
                        break outerloop;
                    }
                }
            } else {
                System.err.println("trying with IPv6 resolving disabled, using " + actual_host);
            }

            if ((InetAddress.getByName(host) instanceof Inet6Address) && (!preferIPv6.isSelected())) {
                System.err.println("prefer IPv6 is not selected but the host supplied is an IPv6 address");
                throw new UnknownHostException("fdsfds");
            }

            ctlSocket = new Socket(actual_host, ctlport);
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + actual_host);
            errmsg = messages.getString("unknownServer") + "\n";
            failed = true;
            return;
        } catch (IOException e) {
            System.err.println("Couldn't get the connection to: " + actual_host + " " + ctlport);
            errmsg = messages.getString("serverNotRunning") + " (" + actual_host + ":" + ctlport + ")\n";
            if (preferIPv6.isSelected()) {
                preferIPv6.setSelected(false);
                continue; //if preferIPv6 is true, we can try once more with false, go again at the start of the for loop
            }
            failed = true;
            return;
        }
        break;//if we made it here, then we need not do the for loop again
    }

    Protocol ctl = new Protocol(ctlSocket);
    Message msg = new Message();

    /* The beginning of the protocol */

    if (ctlSocket.getInetAddress() instanceof Inet6Address) {
        results.append(messages.getString("connected") + " " + host + messages.getString("usingIpv6") + "\n");
    } else {
        results.append(messages.getString("connected") + " " + host + messages.getString("usingIpv4") + "\n");
    }

    /* write our test suite request */
    ctl.send_msg(MSG_LOGIN, tests);
    /* read the specially crafted data that kicks off the old clients */
    if (ctl.readn(msg, 13) != 13) {
        errmsg = messages.getString("unsupportedClient") + "\n";
        failed = true;
        return;
    }

    for (;;) {
        if (ctl.recv_msg(msg) != 0) {
            errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                    + " instead\n";
            failed = true;
            return;
        }
        if (msg.type != SRV_QUEUE) {
            errmsg = messages.getString("loggingWrongMessage") + "\n";
            failed = true;
            return;
        }
        String tmpstr3 = new String(msg.body);
        wait = Integer.parseInt(tmpstr3);
        System.out.println("wait flag received = " + wait);

        if (wait == 0) {
            break;
        }

        if (wait == 9988) {
            if (swait == 0) {
                errmsg = messages.getString("serverBusy") + "\n";
                failed = true;
                return;
            } else {
                errmsg = messages.getString("serverFault") + "\n";
                failed = true;
                return;
            }
        }

        if (wait == 9999) {
            errmsg = messages.getString("serverBusy60s") + "\n";
            failed = true;
            return;
        }

        if (wait == 9990) { // signal from the server to see if the client is still alive
            ctl.send_msg(MSG_WAITING, tests);
            continue;
        }

        // Each test should take less than 30 seconds, so tell them 45 sec * number of 
        // tests in the queue.
        wait = (wait * 45);
        results.append(messages.getString("otherClient") + wait + messages.getString("seconds") + ".\n");
        swait = 1;
    }

    f.toBack();
    ff.toBack();

    if (ctl.recv_msg(msg) != 0) {
        errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                + " instead\n";
        failed = true;
        return;
    }
    if (msg.type != MSG_LOGIN) {
        errmsg = messages.getString("versionWrongMessage") + "\n";
        failed = true;
        return;
    }

    String vVersion = new String(msg.body);
    if (!vVersion.startsWith("v")) {
        errmsg = messages.getString("incompatibleVersion");
        failed = true;
        return;
    }
    System.out.println("Server version: " + vVersion.substring(1));

    if (ctl.recv_msg(msg) != 0) {
        errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                + " instead\n";
        failed = true;
        return;
    }
    if (msg.type != MSG_LOGIN) {
        errmsg = messages.getString("testsuiteWrongMessage") + "\n";
        failed = true;
        return;
    }
    StringTokenizer tokenizer = new StringTokenizer(new String(msg.body), " ");

    while (tokenizer.hasMoreTokens()) {
        if (sPanel.wantToStop()) {
            ctl.send_msg(MSG_ERROR, "Manually stopped by the user".getBytes());
            ctl.close();
            ctlSocket.close();
            errmsg = "\n" + messages.getString("stopped") + "\n";
            failed = true;
            return;
        }
        int testId = Integer.parseInt(tokenizer.nextToken());
        switch (testId) {
        case TEST_MID:
            sPanel.setText(messages.getString("middlebox"));
            simple_progressBar.setValue(1);
            simple_progressBar.setString(res.getString("step1"));
            progress_completed = 10;
            if (test_mid(ctl)) {
                results.append(errmsg);
                results.append(messages.getString("middleboxFail2") + "\n");
                tests &= (~TEST_MID);
            }
            break;
        case TEST_SFW:
            sPanel.setText(messages.getString("simpleFirewall"));
            simple_progressBar.setValue(2);
            simple_progressBar.setString(res.getString("step2"));
            progress_completed = 20;
            if (test_sfw(ctl)) {
                results.append(errmsg);
                results.append(messages.getString("sfwFail") + "\n");
                tests &= (~TEST_SFW);
            }
            break;
        case TEST_C2S:
            sPanel.setText(messages.getString("c2sThroughput"));
            simple_progressBar.setValue(4);
            simple_progressBar.setString(res.getString("step3"));
            progress_completed = 40;
            if (test_c2s(ctl)) {
                results.append(errmsg);
                results.append(messages.getString("c2sThroughputFailed") + "\n");
                tests &= (~TEST_C2S);
            }
            break;
        case TEST_S2C:
            sPanel.setText(messages.getString("s2cThroughput"));
            simple_progressBar.setValue(7);
            simple_progressBar.setString(res.getString("step4"));
            progress_completed = 70;
            if (test_s2c(ctl, ctlSocket)) {
                results.append(errmsg);
                results.append(messages.getString("s2cThroughputFailed") + "\n");
                tests &= (~TEST_S2C);
            }
            break;
        case TEST_META:
            System.err.println("testing meta!!");
            sPanel.setText(messages.getString("meta"));
            if (test_meta(ctl, isApplication ? app_id : applet_id)) {
                results.append(errmsg);
                results.append(messages.getString("metaFailed") + "\n");
                tests &= (~TEST_META);
            }
            break;
        default:
            errmsg = messages.getString("unknownID") + "\n";
            failed = true;
            return;
        }
    }
    if (sPanel.wantToStop()) {
        ctl.send_msg(MSG_ERROR, "Manually stopped by the user".getBytes());
        ctl.close();
        ctlSocket.close();
        errmsg = messages.getString("stopped") + "\n";
        failed = true;
        return;
    }

    sPanel.setText(messages.getString("receiving"));
    i = 0;

    try {
        for (;;) {
            if (ctl.recv_msg(msg) != 0) {
                errmsg = messages.getString("protocolError") + Integer.parseInt(new String(msg.body), 16)
                        + " instead\n";
                failed = true;
                return;
            }
            if (msg.type == MSG_LOGOUT) {
                break;
            }
            if (msg.type != MSG_RESULTS) {
                errmsg = messages.getString("resultsWrongMessage") + "\n";
                failed = true;
                return;
            }
            tmpstr += new String(msg.body);
            i++;
        }
    } catch (IOException e) {
    }

    if (i == 0) {
        results.append(messages.getString("resultsTimeout") + "\n");
    }
    System.err.println("Calling InetAddress.getLocalHost() twice");
    try {
        diagnosis.append(messages.getString("client") + ": " + InetAddress.getLocalHost() + "\n");
    } catch (SecurityException e) {
        diagnosis.append(messages.getString("client") + ": 127.0.0.1\n");
        results.append(messages.getString("unableToObtainIP") + "\n");
        System.err.println("Unable to obtain local IP address: using 127.0.0.1");
    }

    try {
        emailText += messages.getString("client") + ": " + InetAddress.getLocalHost() + "\n%0A";
    } catch (SecurityException e) {
        emailText += messages.getString("client") + ": " + "127.0.0.1" + "\n%0A";
    }

    ctl.close();
    ctlSocket.close();

    try {
        testResults(tmpstr);
    } catch (Exception ex) {
        results.append(messages.getString("resultsParseError") + "\n");
        results.append(ex + "\n");
    }
    if ((tests & TEST_MID) == TEST_MID) {
        middleboxResults(tmpstr2);
    }

    pub_isReady = "yes";
    pub_errmsg = "All tests completed OK.";
    pub_status = "done";
}