Example usage for java.net InetAddress getLocalHost

List of usage examples for java.net InetAddress getLocalHost

Introduction

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

Prototype

public static InetAddress getLocalHost() throws UnknownHostException 

Source Link

Document

Returns the address of the local host.

Usage

From source file:kina.cql.CqlRecordWriter.java

/**
 * Con//from  ww  w. ja v a  2  s.  c  om
 *
 * @param context
 * @param writeConfig
 */
public CqlRecordWriter(TaskContext context, CassandraKinaConfig writeConfig) {
    this.clients = new HashMap<>();
    this.removedClients = new HashMap<>();
    this.writeConfig = writeConfig;
    this.partitioner = RangeUtils.getPartitioner(writeConfig);
    try {
        this.localhost = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new kina.exceptions.InstantiationException("Cannot resolve local hostname", e);
    }
    init();
}

From source file:com.redhat.rhn.domain.monitoring.satcluster.SatClusterFactory.java

/**
 * Create a new SatCluster (scout)/*from www .j  ava  2s  .com*/
 * @param user who creates the Scout
 * @return new instance
 */
public static SatCluster createSatCluster(User user) {
    SatCluster retval = new SatCluster();
    CommandTarget ct = new CommandTarget();
    ct.setOrg(user.getOrg());
    ct.setTargetType("cluster");
    retval.setCommandTarget(ct);
    retval.setOrg(user.getOrg());
    retval.setPhysicalLocation(PHYSICAL_LOCATION);
    retval.setTargetType(ct.getTargetType());
    retval.setDeployed("1");
    retval.setLastUpdateUser(user.getLogin());
    retval.setLastUpdateDate(new Date());
    try {
        InetAddress ip = InetAddress.getLocalHost();
        boolean haveIpv4 = ip instanceof Inet4Address;
        if (haveIpv4) {
            retval.setVip(ip.getHostAddress());
        } else {
            retval.setVip6(ip.getHostAddress());
        }
        NetworkInterface ni = NetworkInterface.getByInetAddress(ip);
        for (InterfaceAddress ifa : ni.getInterfaceAddresses()) {
            InetAddress ia = ifa.getAddress();
            if ((ia instanceof Inet4Address) != haveIpv4) {
                if (haveIpv4) {
                    retval.setVip6(ia.getHostAddress());
                } else {
                    retval.setVip(ia.getHostAddress());
                }
                break;
            }
        }
    } catch (Exception e) {
        log.warn("Failed to find out IP host addresses. " + "Setting loopback IPs instead.");
        try {
            NetworkInterface ni = NetworkInterface.getByName("lo");
            for (InterfaceAddress ifa : ni.getInterfaceAddresses()) {
                InetAddress ia = ifa.getAddress();
                if (ia instanceof Inet4Address) {
                    if (StringUtils.isEmpty(retval.getVip())) {
                        retval.setVip(ia.getHostAddress());
                    }
                } else { //IPv6
                    if (StringUtils.isEmpty(retval.getVip6())) {
                        retval.setVip6(ia.getHostAddress());
                    }
                }
            }
        } catch (SocketException se) {
            log.fatal("Failed to find out loopback IPs.");
            se.printStackTrace();
        }
    }
    return retval;
}

From source file:com.twitter.hraven.hadoopJobMonitor.metrics.HadoopJobMonitorWebServer.java

public void start(int port) throws IOException {
    LOG.info("Instantiating " + HadoopJobMonitorWebApp.class.getName());
    try {//from w  w  w. j  av a 2 s.com
        HadoopJobMonitorWebApp hadoopJobMonitorWebApp = new HadoopJobMonitorWebApp();
        this.webApp = WebApps.$for("node").at(port).start(hadoopJobMonitorWebApp);
        this.port = this.webApp.httpServer().getPort();
        this.host = InetAddress.getLocalHost().getHostName();
        this.webAddress = this.host + ":" + port;
        LOG.info(HadoopJobMonitorWebApp.class.getName() + " started: " + this.webAddress);
    } catch (Exception e) {
        String msg = HadoopJobMonitorWebApp.class.getName() + " failed to start.";
        LOG.error(msg, e);
        throw new IOException(msg);
    }
}

From source file:com.vip.saturn.job.utils.LocalHostService.java

/**
 * ?Host??.//from  w  w w . jav  a2s  . co m
 * 
 * @return Host??
 */
public static String getHostName() {
    if (!Strings.isNullOrEmpty(cachedHostName)) {
        return cachedHostName;
    } else {
        try {
            cachedHostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {//NOSONAR
            e.printStackTrace();//NOSONAR
            return ERROR_HOSTNAME;
        }
        return cachedHostName;
    }
}

From source file:fr.aliasource.webmail.sending.SendAction.java

public void execute(IProxy p, IParameterSource req, IResponder responder) {
    String xmlMessage = req.getParameter("message");

    // reply infos
    String uid = req.getParameter("uid");
    String folder = req.getParameter("folder");
    SendParameters sp = SendParametersFactory.createFromParamsMap(req);
    logger.info(sp.toString());/*from   w ww.j  av a 2s.c o m*/

    IAccount ac = p.getAccount();
    MailMessage mm = new XmlMailMessageParser().parse(xmlMessage);
    List<Address> recipients = getAllRistrettoRecipients(mm);

    try {
        SMTPProtocol smtp = new SMTPProtocol(ac.getTransportHost());
        Mime4jFormatter mf = new Mime4jFormatter(ac);

        smtp.openPort();
        smtp.ehlo(InetAddress.getLocalHost());
        smtp.mail(ristrettoAddr(mm.getSender()));

        for (Address to : recipients) {
            logger.info("to.display: " + to.getDisplayName() + " mail: " + to.getMailAddress());
            Address cleaned = new Address(to.getMailAddress());
            smtp.rcpt(cleaned);
        }

        if (uid != null && folder != null) {
            String[] replyInformations = getOrigMessageId(ac, folder, uid);
            String messageId = replyInformations != null ? replyInformations[0] : null;
            String references = buildReferences(replyInformations);
            smtp.data(mf.format(mm, messageId, references, sp));
        } else {
            smtp.data(mf.format(mm, sp));
        }
        smtp.quit();

    } catch (SMTPException se) {
        logger.error(se.getMessage());
        responder.sendError(se.getMessage());
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        responder.sendError("[mail-send-error] " + e.getMessage());
        return;
    }

    try {
        collectAddresses(ac, recipients);
    } catch (Throwable t) {
        logger.error(t.getMessage(), t);
    }

    responder.sendString("OK");

}

From source file:com.microsoft.alm.plugin.idea.services.TelemetryContextInitializer.java

private String getComputerName() {
    String hostname = "Unknown";

    try {//from ww w .  ja va 2  s  . com
        final InetAddress address = InetAddress.getLocalHost();
        hostname = address.getHostName();
    } catch (UnknownHostException ex) {
        // This case is covered by the initial value of hostname above
    }

    return hostname;
}

From source file:de.fhg.iais.asc.ui.MyCortexStarter.java

private static void configureLogging() {
    String hostAddress = "n/a";
    try {// w  ww . j a  v a  2  s  .com
        hostAddress = InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        LOG.warn("Hostname/IP not available");
    }
    MDC.put("host_name", hostAddress);

    // SLF4J is bound to logback
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(lc);
        lc.reset();
        configurator.doConfigure("conf/logback.xml");
    } catch (JoranException je) {
        je.printStackTrace(); // NOSONAR
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(lc);

    LOG.info("-- CORTEX starting");

    java.util.logging.Logger rootLogger = LogManager.getLogManager().getLogger("");
    Handler[] handlers = rootLogger.getHandlers();
    for (Handler handler : handlers) {
        rootLogger.removeHandler(handler);
    }
    SLF4JBridgeHandler.install();
}

From source file:com.codemacro.jcm.test.TestCluster.java

public void testOther() throws UnknownHostException {
    System.out.println(InetAddress.getLocalHost().getHostAddress());
}

From source file:de.pawlidi.openaletheia.utils.AletheiaUtils.java

private static String getLocalhostAddress() {
    String localhostAdress = null;
    try {/* w w w.j  av  a  2 s  .  co m*/
        final InetAddress localHost = InetAddress.getLocalHost();
        if (localHost != null) {
            localhostAdress = localHost.getHostAddress();
        }
    } catch (UnknownHostException ex) {
        // ignore exception
    }
    return localhostAdress;
}

From source file:acromusashi.stream.hook.AmLogServerAdapter.java

/**
 * Initialize WebSocket server.//from  www  .j  a va  2s  .c om
 * 
 * @param serverPort serverPort
 */
public synchronized void init(int serverPort) {
    if (this.initialized) {
        return;
    }

    String hostname = null;

    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException ex) {
        logger.warn("Get host failed. Use localhost.", ex);
    }

    logger.info("WebSocket server initialize. : HostName={}, Port={}, Path={}, Object={}", hostname, serverPort,
            "/", this.toString());
    this.server = new Server(hostname, serverPort, "/", null, AmLogServerEndPoint.class);
    try {
        this.server.start();
    } catch (DeploymentException ex) {
        logger.warn("WebSocket server initialize failed. Skip initialize.", ex);
    }

    this.initialized = true;
}