Example usage for java.net InetAddress getHostName

List of usage examples for java.net InetAddress getHostName

Introduction

In this page you can find the example usage for java.net InetAddress getHostName.

Prototype

public String getHostName() 

Source Link

Document

Gets the host name for this IP address.

Usage

From source file:org.mule.test.firewall.FirewallTestCase.java

protected String name(InetAddress address, boolean canonical) {
    if (canonical) {
        return address.getCanonicalHostName();
    } else {/*from w w  w  .j ava2 s.c o  m*/
        return address.getHostName();
    }
}

From source file:com.clustercontrol.port.protocol.ReachAddressSMTPS.java

/**
 * SMTPS????????//from w ww  .java 2s  .c o  m
 * 
 * @param addressText
 * @return SMTPS
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the SMTPS Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        SMTPSClient client = new SMTPSClient(true);

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (SMTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(SMTPS/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.warn("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage(), e);

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.melusyn.sendgrid.SendGridMod.java

@Override
public void start() {
    super.start();
    EventBus eb = vertx.eventBus();/*from ww w.ja v  a 2s .  co  m*/

    String address = getOptionalStringConfig("address", "melusyn.sendgrid");
    String sendgridUsername = getMandatoryStringConfig("sendgrid_username");
    String sendgridPassword = getMandatoryStringConfig("sendgrid_password");

    JsonObject suppressionJson = container.config().getObject("suppressions", new JsonObject());
    for (String templateId : suppressionJson.getFieldNames()) {
        templateSuppressionGroup.put(templateId, suppressionJson.getInteger(templateId));
    }

    try {
        InetAddress ip = InetAddress.getLocalHost();
        hostname = ip.getHostName();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }

    sendgrid = new SendGrid(sendgridUsername, sendgridPassword);

    eb.registerHandler(address + ".send", this::sendEmail);
    eb.registerHandler(address + ".sendv2", this::sendEmailV2);
}

From source file:com.clustercontrol.port.protocol.ReachAddressTCP.java

/**
 * ????????????//  ww w .  j  a  v  a2 s  . c  o m
 * 
 * @param addressText
 * @return PORT
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        // Reachability ?? ICMP ??
        boolean retry = true;

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the port of " + address.getHostName() + "[" + address.getHostAddress()
                + "]:" + m_portNo + ".\n\n");

        // 
        Socket socket = null;

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                // ?
                socket = new Socket();
                InetSocketAddress isa = new InetSocketAddress(address, m_portNo);

                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                start = HinemosTime.currentTimeMillis();
                socket.connect(isa, m_timeout);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;
                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = ("Response Time < 1ms");
                }
                retry = false;
                isReachable = true;
            } catch (BindException e) {
                result = (e.getMessage() + "[BindException]");
                retry = true;
                isReachable = false;
            } catch (ConnectException e) {
                result = (e.getMessage() + "[ConnectException]");
                retry = false;
                isReachable = false;
            } catch (NoRouteToHostException e) {
                result = (e.getMessage() + "[NoRouteToHostException]");
                retry = true;
                isReachable = false;
            } catch (PortUnreachableException e) {
                result = (e.getMessage() + "[PortUnreachableException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket close failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(TCP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:org.sipfoundry.preflight.NTP.java

/**
 * Process <code>TimeInfo</code> object and return details.
 *
 * @param info/* w w  w .j a  v  a  2s  . co  m*/
 *            <code>TimeInfo</code> object.
 */
private String processResponse(TimeInfo info) {
    String response;
    NtpV3Packet message = info.getMessage();
    int stratum = message.getStratum();
    String refType;
    if (stratum <= 0) {
        refType = "(Unspecified or Unavailable)";
    } else if (stratum == 1) {
        refType = "(Primary Reference; e.g., GPS)"; // GPS, radio clock,
                                                    // etc.
    } else {
        refType = "(Secondary Reference; e.g. via NTP or SNTP)";
    }
    // stratum should be 0..15...
    response = new String("  Stratum: " + stratum + " " + refType + "\n");
    int version = message.getVersion();
    int li = message.getLeapIndicator();
    response += new String(
            "  leap=" + li + ", version=" + version + ", precision=" + message.getPrecision() + "\n");

    response += new String("  mode: " + message.getModeName() + " (" + message.getMode() + ")\n");
    int poll = message.getPoll();
    // poll value typically btwn MINPOLL (4) and MAXPOLL (14)
    response += new String(
            "  poll: " + (poll <= 0 ? 1 : (int) Math.pow(2, poll)) + " seconds" + " (2 ** " + poll + ")\n");
    double disp = message.getRootDispersionInMillisDouble();
    response += new String("  rootdelay=" + numberFormat.format(message.getRootDelayInMillisDouble())
            + ", rootdispersion(ms): " + numberFormat.format(disp) + "\n");

    int refId = message.getReferenceId();
    String refAddr = NtpUtils.getHostAddress(refId);
    String refName = null;
    if (refId != 0) {
        if (refAddr.equals("127.127.1.0")) {
            refName = "LOCAL"; // This is the ref address for the Local
                               // Clock
        } else if (stratum >= 2) {
            // If reference id has 127.127 prefix then it uses its own
            // reference clock
            // defined in the form 127.127.clock-type.unit-num (e.g.
            // 127.127.8.0 mode 5
            // for GENERIC DCF77 AM; see refclock.htm from the NTP software
            // distribution.
            if (!refAddr.startsWith("127.127")) {
                try {
                    InetAddress addr = InetAddress.getByName(refAddr);
                    String name = addr.getHostName();
                    if (name != null && !name.equals(refAddr)) {
                        refName = name;
                    }
                } catch (UnknownHostException e) {
                    // some stratum-2 servers sync to ref clock device but
                    // fudge stratum level higher... (e.g. 2)
                    // ref not valid host maybe it's a reference clock name?
                    // otherwise just show the ref IP address.
                    refName = NtpUtils.getReferenceClock(message);
                }
            }
        } else if (version >= 3 && (stratum == 0 || stratum == 1)) {
            refName = NtpUtils.getReferenceClock(message);
            // refname usually have at least 3 characters (e.g. GPS, WWV,
            // LCL, etc.)
        }
        // otherwise give up on naming the beast...
    }
    if (refName != null && refName.length() > 1) {
        refAddr += " (" + refName + ")";
    }
    response += new String("  Reference Identifier:  " + refAddr + "\n");

    TimeStamp refNtpTime = message.getReferenceTimeStamp();
    response += new String("  Reference Timestamp:   " + refNtpTime + "  " + refNtpTime.toDateString() + "\n");

    // Originate Time is time request sent by client (t1)
    TimeStamp origNtpTime = message.getOriginateTimeStamp();
    response += new String(
            "  Originate Timestamp:   " + origNtpTime + "  " + origNtpTime.toDateString() + "\n");

    long destTime = info.getReturnTime();
    // Receive Time is time request received by server (t2)
    TimeStamp rcvNtpTime = message.getReceiveTimeStamp();
    response += new String("  Receive Timestamp:     " + rcvNtpTime + "  " + rcvNtpTime.toDateString() + "\n");

    // Transmit time is time reply sent by server (t3)
    TimeStamp xmitNtpTime = message.getTransmitTimeStamp();
    response += new String(
            "  Transmit Timestamp:    " + xmitNtpTime + "  " + xmitNtpTime.toDateString() + "\n");

    // Destination time is time reply received by client (t4)
    TimeStamp destNtpTime = TimeStamp.getNtpTime(destTime);
    response += new String(
            "  Destination Timestamp: " + destNtpTime + "  " + destNtpTime.toDateString() + "\n");

    info.computeDetails(); // compute offset/delay if not already done
    Long offsetValue = info.getOffset();
    Long delayValue = info.getDelay();
    String delay = (delayValue == null) ? "N/A" : delayValue.toString();
    String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

    response += new String("  Roundtrip delay(ms)=" + delay + ", clock offset(ms)=" + offset + "\n"); // offset
                                                                                                      // in
                                                                                                      // ms

    return response;
}

From source file:org.apache.hadoop.hbase.regionserver.TestRegionServerHostname.java

@Test(timeout = 120000)
public void testRegionServerHostname() throws Exception {
    final int NUM_MASTERS = 1;
    final int NUM_RS = 1;
    Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces();

    while (netInterfaceList.hasMoreElements()) {
        NetworkInterface ni = netInterfaceList.nextElement();
        Enumeration<InetAddress> addrList = ni.getInetAddresses();
        // iterate through host addresses and use each as hostname
        while (addrList.hasMoreElements()) {
            InetAddress addr = addrList.nextElement();
            if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress()) {
                continue;
            }/*from w  w  w.j a  va  2s.co m*/
            String hostName = addr.getHostName();
            LOG.info("Found " + hostName + " on " + ni);

            TEST_UTIL.getConfiguration().set(HRegionServer.MASTER_HOSTNAME_KEY, hostName);
            TEST_UTIL.getConfiguration().set(HRegionServer.RS_HOSTNAME_KEY, hostName);
            TEST_UTIL.startMiniCluster(NUM_MASTERS, NUM_RS);
            try {
                ZooKeeperWatcher zkw = TEST_UTIL.getZooKeeperWatcher();
                List<String> servers = ZKUtil.listChildrenNoWatch(zkw, zkw.rsZNode);
                // there would be NUM_RS+1 children - one for the master
                assertTrue(servers.size() == NUM_RS + 1);
                for (String server : servers) {
                    assertTrue("From zookeeper: " + server + " hostname: " + hostName,
                            server.startsWith(hostName.toLowerCase() + ","));
                }
                zkw.close();
            } finally {
                TEST_UTIL.shutdownMiniCluster();
            }
        }
    }
}

From source file:org.springframework.amqp.rabbit.connection.SingleConnectionFactory.java

private String getDefaultHostName() {
    String temp;/*from  w  w w  .  ja v  a2 s .co m*/
    try {
        InetAddress localMachine = InetAddress.getLocalHost();
        temp = localMachine.getHostName();
        logger.debug("Using hostname [" + temp + "] for hostname.");
    } catch (UnknownHostException e) {
        logger.warn("Could not get host name, using 'localhost' as default value", e);
        temp = "localhost";
    }
    return temp;
}

From source file:org.apache.synapse.startup.quartz.SimpleQuartz.java

public void init(SynapseEnvironment synapseEnvironment) {

    if (taskDescription == null) {
        handleException("Error while initializing the startup. TaskDescription is null.");
    }/*www.  j  av a  2  s  .com*/

    taskManager = synapseEnvironment.getTaskManager();

    if (!taskManager.isInitialized()) {
        log.warn("SynapseTaskManager is not properly initialized. Initializing now with "
                + "default parameters.");
        taskManager.init(null, null);
    }

    TaskDescriptionRepository repository = taskManager.getTaskDescriptionRepository();

    if (repository == null) {
        handleException("Task Description Repository cannot be found");
        return;
    }

    repository.addTaskDescription(taskDescription);

    // this server name given by system property SynapseServerName
    // otherwise take host-name
    // else assume localhost
    String thisServerName = synapseEnvironment.getServerContextInformation().getServerConfigurationInformation()
            .getServerName();
    if (thisServerName == null || thisServerName.equals("")) {
        try {
            InetAddress address = InetAddress.getLocalHost();
            thisServerName = address.getHostName();

        } catch (UnknownHostException e) {
            log.warn("Could not get the host name", e);
        }

        if (thisServerName == null || thisServerName.equals("")) {
            thisServerName = "localhost";
        }
    }
    log.debug("Synapse server name : " + thisServerName);

    // start proxy service if either,
    // pinned server name list is empty
    // or pinned server list has this server name
    List pinnedServers = taskDescription.getPinnedServers();
    if (pinnedServers != null && !pinnedServers.isEmpty()) {
        if (!pinnedServers.contains(thisServerName)) {
            log.info("Server name not in pinned servers list. Not starting Task : " + getName());
            return;
        }
    }

    try {
        task = (Task) getClass().getClassLoader().loadClass(taskDescription.getTaskClass()).newInstance();
    } catch (Exception e) {
        handleException("Cannot instantiate task : " + taskDescription.getTaskClass(), e);
    }

    Set properties = taskDescription.getProperties();
    for (Object property : properties) {
        OMElement prop = (OMElement) property;
        log.debug("Found Property : " + prop.toString());
        PropertyHelper.setStaticProperty(prop, task);
    }

    if (task instanceof ManagedLifecycle) {
        ((ManagedLifecycle) task).init(synapseEnvironment);
    }

    Map<String, Object> map = new HashMap<String, Object>();
    map.put(SimpleQuartzJob.SYNAPSE_ENVIRONMENT, synapseEnvironment);

    try {

        TaskScheduler taskScheduler = taskManager.getTaskScheduler();
        if (taskScheduler != null) {
            if (!taskScheduler.isInitialized()) {
                taskScheduler.init(synapseEnvironment.getSynapseConfiguration().getProperties());
            }
            taskScheduler.scheduleTask(taskDescription, map, SimpleQuartzJob.class, task);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("TaskScheduler cannot be found for :" + TaskConstants.TASK_SCHEDULER + " , "
                        + "therefore ignore scheduling of Task  " + taskDescription);
            }
        }

    } catch (Exception e) {
        String msg = "Error starting up Scheduler : " + e.getMessage();
        log.fatal(msg, e);
        throw new SynapseException(msg, e);
    }

}

From source file:org.apache.hadoop.mapred.TestNodeDecommissioning.java

/**
 * This tests whether a node is successfully able to be
 * decommissioned or not.//from   w  ww.j a  va  2 s .com
 * First a node is decommissioned and verified.
 * Then it is removed from decommissoned and verified again.
 * At last the node is started.
 */
@Test
public void TestNodeDecommissioning() throws Exception {

    JTProtocol remoteJTClientProxy = cluster.getJTClient().getProxy();

    JTClient remoteJTClient = cluster.getJTClient();
    String jtClientHostName = remoteJTClient.getHostName();
    InetAddress localMachine = java.net.InetAddress.getLocalHost();
    String testRunningHostName = localMachine.getHostName();
    LOG.info("Hostname of local machine: " + testRunningHostName);

    List<TTClient> ttClients = cluster.getTTClients();

    //One slave is got
    TTClient ttClient = (TTClient) ttClients.get(0);
    String ttClientHostName = ttClient.getHostName();

    //Hadoop Conf directory is got
    String hadoopConfDir = cluster.getConf().get(HadoopDaemonRemoteCluster.CONF_HADOOPCONFDIR);

    LOG.info("hadoopConfDir is:" + hadoopConfDir);

    //Hadoop Home is got
    String hadoopHomeDir = cluster.getConf().get(HadoopDaemonRemoteCluster.CONF_HADOOPHOME);

    LOG.info("hadoopHomeDir is:" + hadoopHomeDir);

    conf = cluster.getJTClient().getProxy().getDaemonConf();
    //"mapred.hosts.exclude" path is got
    String excludeHostPathString = (String) conf.get("mapred.hosts.exclude");
    String keytabForHadoopqaUser = "/homes/hadoopqa/hadoopqa.dev.headless.keytab hadoopqa";
    excludeHostPath = new Path(excludeHostPathString);
    LOG.info("exclude Host pathString is :" + excludeHostPathString);

    //One sleep job is submitted
    SleepJob job = new SleepJob();
    job.setConf(conf);
    conf = job.setupJobConf(1, 0, 100, 100, 100, 100);
    JobConf jconf = new JobConf(conf);
    RunningJob rJob = cluster.getJTClient().getClient().submitJob(jconf);

    //username who submitted the job is got.
    String userName = null;
    try {
        JobStatus[] jobStatus = cluster.getJTClient().getClient().getAllJobs();
        userName = jobStatus[0].getUsername();
    } catch (Exception ex) {
        LOG.error("Failed to get user name");
        boolean status = false;
        Assert.assertTrue("Failed to get the userName", status);
    }

    //The client which needs to be decommissioned is put in the exclude path. 
    String command = "echo " + ttClientHostName + " > " + excludeHostPath;

    LOG.info("command is : " + command);
    RemoteExecution rExec = new SSHRemoteExecution();
    rExec.executeCommand(jtClientHostName, userName, command);

    //The refreshNode command is created and execute in Job Tracker Client.
    String refreshNodeCommand = "export HADOOP_CONF_DIR=" + hadoopConfDir + "; export HADOOP_HOME="
            + hadoopHomeDir + ";cd " + hadoopHomeDir + ";kinit -k -t " + keytabForHadoopqaUser
            + ";bin/hadoop mradmin -refreshNodes;";
    LOG.info("refreshNodeCommand is : " + refreshNodeCommand);
    try {
        rExec.executeCommand(testRunningHostName, userName, refreshNodeCommand);
    } catch (Exception e) {
        e.printStackTrace();
    }

    //Checked whether the node is really decommissioned.
    boolean nodeDecommissionedOrNot = false;
    nodeDecommissionedOrNot = remoteJTClientProxy.isNodeDecommissioned(ttClientHostName);

    //The TTClient host is removed from the exclude path
    command = "rm " + excludeHostPath;

    LOG.info("command is : " + command);
    rExec.executeCommand(jtClientHostName, userName, command);

    Assert.assertTrue("Node should be decommissioned", nodeDecommissionedOrNot);

    //The refreshNode command is created and execute in Job Tracker Client.
    rExec.executeCommand(jtClientHostName, userName, refreshNodeCommand);

    //Checked whether the node is out of decommission.
    nodeDecommissionedOrNot = false;
    nodeDecommissionedOrNot = remoteJTClientProxy.isNodeDecommissioned(ttClientHostName);
    Assert.assertFalse("present of not is", nodeDecommissionedOrNot);

    //Starting that node
    String ttClientStart = "export HADOOP_CONF_DIR=" + hadoopConfDir + "; export HADOOP_HOME=" + hadoopHomeDir
            + ";cd " + hadoopHomeDir + ";kinit -k -t " + keytabForHadoopqaUser
            + ";bin/hadoop-daemons.sh start tasktracker;";
    LOG.info("ttClientStart is : " + ttClientStart);
    rExec.executeCommand(jtClientHostName, userName, ttClientStart);
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContextCollection.java

@Override
public Socket createSocket(InetAddress host, int port, int connectTimeout) throws IOException {
    return getSSLContextForHostname(host.getHostName()).createSocket(host, port, connectTimeout);
}