Example usage for java.net UnknownHostException getMessage

List of usage examples for java.net UnknownHostException getMessage

Introduction

In this page you can find the example usage for java.net UnknownHostException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

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 va2  s  . c o  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:me.adaptive.core.metrics.ServerMetricsProducer.java

@Scheduled(fixedRate = 30000)
public void sendServerMetrics() {

    MetricServerEntity metricServer = new MetricServerEntity();
    Map<String, String> attributes = new HashMap<String, String>();

    // Hostname/*from  www.j  ava  2  s  .  co  m*/
    try {
        metricServer.setHostname(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        metricServer.setHostname("undefined");
        System.out.println(e.getMessage());
    }

    SystemInfo si = new SystemInfo();
    HardwareAbstractionLayer hal = si.getHardware();

    // Memory
    Long memAvailable = hal.getMemory().getAvailable();
    Long memUsed = hal.getMemory().getTotal() - memAvailable;
    attributes.put(Constants.MEM_USED, String.valueOf(memUsed));
    attributes.put(Constants.MEM_AVAILABLE, String.valueOf(memAvailable));

    // CPU
    // Get the first CPU to get the system load at that time
    Double systemLoad = hal.getProcessors()[0].getSystemCpuLoad();
    attributes.put(Constants.SYSTEM_CPU_LOAD, String.valueOf(systemLoad));

    // FileSystem
    // Get the first FileSystem supposing there is only one disk
    Long diskAvailable = hal.getFileStores()[0].getUsableSpace();
    Long diskUsed = hal.getFileStores()[0].getTotalSpace() - diskAvailable;
    attributes.put(Constants.DISK_USED, String.valueOf(diskUsed));
    attributes.put(Constants.DISK_AVAILABLE, String.valueOf(diskAvailable));

    metricServer.setAttributes(attributes);

    this.jmsTemplate.convertAndSend(metricServer);
}

From source file:org.apache.carbondata.core.dictionary.service.AbstractDictionaryServer.java

public String findLocalIpAddress(Logger LOGGER) {
    try {//from  w  w w. j  a  va  2  s .  co m
        String defaultIpOverride = System.getenv("SPARK_LOCAL_IP");
        if (defaultIpOverride != null) {
            return defaultIpOverride;
        } else {
            InetAddress address = InetAddress.getLocalHost();
            if (address.isLoopbackAddress()) {
                // Address resolves to something like 127.0.1.1, which happens on Debian; try to find
                // a better address using the local network interfaces
                // getNetworkInterfaces returns ifs in reverse order compared to ifconfig output order
                // on unix-like system. On windows, it returns in index order.
                // It's more proper to pick ip address following system output order.
                Enumeration<NetworkInterface> activeNetworkIFs = NetworkInterface.getNetworkInterfaces();
                List<NetworkInterface> reOrderedNetworkIFs = new ArrayList<NetworkInterface>();
                while (activeNetworkIFs.hasMoreElements()) {
                    reOrderedNetworkIFs.add(activeNetworkIFs.nextElement());
                }

                if (!SystemUtils.IS_OS_WINDOWS) {
                    Collections.reverse(reOrderedNetworkIFs);
                }

                for (NetworkInterface ni : reOrderedNetworkIFs) {
                    Enumeration<InetAddress> inetAddresses = ni.getInetAddresses();
                    while (inetAddresses.hasMoreElements()) {
                        InetAddress addr = inetAddresses.nextElement();
                        if (!addr.isLinkLocalAddress() && !addr.isLoopbackAddress()
                                && addr instanceof Inet4Address) {
                            // We've found an address that looks reasonable!
                            LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                                    + " resolves to a loopback address: " + address.getHostAddress()
                                    + "; using " + addr.getHostAddress() + " instead (on interface "
                                    + ni.getName() + ")");
                            LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                            return addr.getHostAddress();
                        }
                    }
                    LOGGER.warn("Your hostname, " + InetAddress.getLocalHost().getHostName()
                            + " resolves to a loopback address: " + address.getHostAddress()
                            + ", but we couldn't find any external IP address!");
                    LOGGER.warn("Set SPARK_LOCAL_IP if you need to bind to another address");
                }
            }
            return address.getHostAddress();
        }
    } catch (UnknownHostException e) {
        LOGGER.error("do not get local host address:" + e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (SocketException e) {
        LOGGER.error("do not get net work interface:" + e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:org.openhab.binding.powermax.internal.connector.PowermaxTcpConnector.java

@Override
public void open() {
    logger.debug("open(): Opening TCP Connection");

    try {// w w w .  ja  v a2  s  .com
        tcpSocket = new Socket();
        tcpSocket.setSoTimeout(250);
        SocketAddress socketAddress = new InetSocketAddress(ipAddress, tcpPort);
        tcpSocket.connect(socketAddress, connectTimeout);

        setInput(tcpSocket.getInputStream());
        setOutput(tcpSocket.getOutputStream());

        setReaderThread(new PowermaxReaderThread(this));
        getReaderThread().start();

        setConnected(true);
    } catch (UnknownHostException e) {
        logger.debug("open(): Unknown Host Exception: {}", e.getMessage(), e);
        setConnected(false);
    } catch (SocketException e) {
        logger.debug("open(): Socket Exception: {}", e.getMessage(), e);
        setConnected(false);
    } catch (IOException e) {
        logger.debug("open(): IO Exception: {}", e.getMessage(), e);
        setConnected(false);
    } catch (Exception e) {
        logger.debug("open(): Exception: {}", e.getMessage(), e);
        setConnected(false);
    }
}

From source file:dk.dma.epd.common.prototype.sensor.nmea.NmeaTcpSensor.java

private void connect() throws IOException {
    try {/*from   w w  w.  ja  v a 2s .  c  o  m*/
        clientSocket = new Socket();
        InetSocketAddress address = new InetSocketAddress(hostname, port);
        clientSocket.connect(address);
        clientSocket.setKeepAlive(true);
        clientSocket.setSoTimeout(TCP_READ_TIMEOUT);
        outputStream = clientSocket.getOutputStream();
        LOG.info("NMEA source connected " + hostname + ":" + port);
    } catch (UnknownHostException e) {
        LOG.error("Unknown host: " + hostname + ": " + e.getMessage());
        throw e;
    } catch (IOException e) {
        LOG.error("Could not connect to NMEA source: " + hostname + ": " + e.getMessage());
        throw e;
    }
}

From source file:gov.hhs.fha.nhinc.lift.ServerApp.java

private InetSocketAddress createSocketAddr() {
    InetSocketAddress addr = null;
    String proxyAddr = "";
    String proxyPort = "";
    try {/*  w w  w  .  j av a2 s  .  c o  m*/
        proxyAddr = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_PROXY_ADDRESS);
        proxyPort = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
                NhincConstants.LIFT_PROXY_PORT);
        int portNum = Integer.parseInt(proxyPort);

        InetAddress inetAddr = InetAddress.getByName(proxyAddr);
        addr = new InetSocketAddress(inetAddr, portNum);
        log.debug("LiFT Server Address defined as: " + addr.toString());
    } catch (UnknownHostException ex) {
        log.error("Unknown LiFT Proxy Address and Port " + proxyAddr + ":" + proxyPort + " " + ex.getMessage());
    } catch (PropertyAccessException ex) {
        log.error("Missing LiFT Proxy Address and Port Properties " + ex.getMessage());
    }
    return addr;
}

From source file:info.magnolia.init.DefaultMagnoliaInitPaths.java

/**
 * Figures out the local host name, makes sure it's lowercase, and use its unqualified name if the {@value #MAGNOLIA_UNQUALIFIED_SERVER_NAME} init parameter is set to true.
 *//*from w  ww.  j av a  2 s. c  om*/
protected String determineServerName(ServletContext context) {
    final boolean unqualifiedServerName = BooleanUtils
            .toBoolean(context.getInitParameter(MAGNOLIA_UNQUALIFIED_SERVER_NAME));
    final String retroCompatMethodCall = magnoliaServletContextListener.initServername(unqualifiedServerName);
    if (retroCompatMethodCall != null) {
        DeprecationUtil.isDeprecated(
                "You should update your code and override determineServerName(ServletContext) instead of initServername(String)");
        return retroCompatMethodCall;
    }

    try {
        String serverName = StringUtils.lowerCase(InetAddress.getLocalHost().getHostName());

        if (unqualifiedServerName && StringUtils.contains(serverName, ".")) {
            serverName = StringUtils.substringBefore(serverName, ".");
        }
        return serverName;
    } catch (UnknownHostException e) {
        log.error(e.getMessage());
        return null;
    }
}

From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java

public static URL resolveServiceEndpoint(String scheme, String serviceName, String defaultPort) {
    URL endpoint = null;/*from ww  w .  ja  v  a2 s .  c  o m*/
    String host = null;
    String port = defaultPort;
    try {
        //lookup in the current namespace
        log.info("Looking up service " + serviceName);
        InetAddress initAddress = InetAddress.getByName(serviceName);
        host = initAddress.getCanonicalHostName();
        log.debug("Resolved host using DNS: " + host);
    } catch (UnknownHostException e) {
        log.debug("Could not resolve DNS for " + serviceName + ", trying ENV settings next.");
        host = KubernetesServices.serviceToHostOrBlank(serviceName);
        if ("".equals(host)) {
            return null;
        } else {
            log.debug("Resolved " + serviceName + " host using ENV: " + host);
        }
    }
    port = KubernetesServices.serviceToPortOrBlank(serviceName);
    if ("".equals(port)) {
        port = defaultPort;
        log.debug("Defaulting " + serviceName + " port to: " + port);
    } else {
        log.debug("Resolved " + serviceName + " port using ENV: " + port);
    }

    if (scheme == null) {
        if (port.endsWith("443"))
            scheme = "https";
        else
            scheme = "http";
    }
    try {
        endpoint = new URL(scheme, host, Integer.valueOf(port), "");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return endpoint;
}

From source file:net.sqs2.omr.task.broker.RemoteTaskExecutorManager.java

private TaskBroker createRemoteTaskBroker(String uriString, long remoteKey, long sessionID) {
    try {/*from  w ww  .  j  a v  a2  s.  c  o  m*/
        URI uri = new URI(uriString);

        if (NetworkUtil.isMyAddress(InetAddress.getAllByName(uri.getHost()))) {
            return null;
        }

        RemoteSessionService sessionService = (RemoteSessionService) Naming.lookup(uri.toString()); // connect to remote SessionService
        long result = sessionService.ping(remoteKey); // authentication
        if (DEBUG) {
            Logger.getLogger("executor").info("RemoteSessionService.URI=" + uri);
            Logger.getLogger("executor").info("Hello=" + result);
        }
        TaskBroker remoteTaskBroker = new TaskBroker("Remote", this.manager,
                new TaskExecutorEnv(null, sessionService, remoteKey, sessionID));
        return remoteTaskBroker;
    } catch (UnknownHostException ex) {
        Logger.getLogger("executor").severe("UnknownHostException:" + ex.getMessage());
    } catch (SocketException ex) {
        Logger.getLogger("executor").severe("SocketException:" + ex.getMessage());
    } catch (URISyntaxException ex) {
        Logger.getLogger("executor").severe("URISyntaxException:" + ex.getMessage());
    } catch (ConnectException ex) {
        Logger.getLogger("executor").severe("ConnectException:" + ex.getMessage());
    } catch (RemoteException ex) {
        Logger.getLogger("executor").severe("RemoteException:" + ex.getMessage());
    } catch (MalformedURLException ex) {
        Logger.getLogger("executor").severe("MalformedURLException:" + ex.getMessage());
    } catch (NotBoundException ex) {
        Logger.getLogger("executor").severe("NotBoundException:" + ex.getMessage());
    }
    return null;
}

From source file:com.bitcup.configurator.Context.java

private String getLocalHostName() {
    String hostname = null;/*from w  w w  . ja v a2  s. c om*/
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        logger.error("Unable to infer hostname from InetAddress.getLocalHost().getHostName()", e.getMessage());
    }
    return hostname;
}