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:com.baidu.rigel.biplatform.cache.store.service.impl.HazelcastStoreManager.java

/**
 * HZ??HZ/*  w ww  .jav  a 2  s  .c om*/
 * 
 * @param configPath
 *            hz?
 */
public HazelcastStoreManager(HazelcastProperties hazelcastProperties) {
    //        Properties prop = new Properties();
    //        try {
    //            prop = loadConf(null);
    //        } catch (IOException e) {
    //            LOGGER.warn("load conf error,use default config");
    //        }
    Config cfg = new Config();
    cfg.getGroupConfig().setName(hazelcastProperties.getGroupUserName());
    cfg.getGroupConfig().setPassword(hazelcastProperties.getGroupPassword());

    cfg.setInstanceName(hazelcastProperties.getInstanceName());

    // cfg.getQueueConfig(EVENT_QUEUE).addItemListenerConfig(new ItemListenerConfig(this.hazelcastQueueItemListener,true));
    if (hazelcastProperties.getMancenter().isEnable()
            && StringUtils.isNotBlank(hazelcastProperties.getMancenter().getUrl())) {
        cfg.getManagementCenterConfig().setEnabled(true);
        cfg.getManagementCenterConfig().setUrl(hazelcastProperties.getMancenter().getUrl());
    }
    System.setProperty("hazelcast.socket.bind.any", "false");
    String ip = "127.0.0.1";
    try {
        ip = InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        LOGGER.warn("get ip error, {}", e.getMessage());
    }
    LOGGER.info("local memchine ip: {}", ip);
    cfg.getProperties();//.getGroupProperties().SOCKET_SERVER_BIND_ANY
    cfg.getNetworkConfig().getInterfaces().addInterface(ip);
    cfg.getNetworkConfig().getInterfaces().setEnabled(true);

    JoinConfig join = cfg.getNetworkConfig().getJoin();
    TcpIpConfig tcpIpConfig = join.getTcpIpConfig();
    tcpIpConfig.addMember(hazelcastProperties.getMembers());
    if (!tcpIpConfig.getMembers().contains("127.0.0.1")) {
        tcpIpConfig.addMember("127.0.0.1");
    }
    LOGGER.info("hazelcast members in prop:{}", tcpIpConfig.getMembers());
    tcpIpConfig.setEnabled(true);
    this.hazelcast = Hazelcast.newHazelcastInstance(cfg);
    this.cacheManager = new HazelcastCacheManager(this.hazelcast);
}

From source file:org.nuxeo.connect.connector.http.proxy.NashornProxyPacResolver.java

public static String myIpAddress() {
    try {//  ww  w  .j a va  2  s.  c om
        return InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        return "127.0.0.1";
    }
}

From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java

@Override
public void run() {
    try {/*from w  w w  . j av a  2s.  c o m*/
        // Send TASK_RUNNING
        sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot");

        if (Objects.equals(context.getRestoreType(), new String("new"))) {
            final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName()
                    + File.separator + context.getNodeId();

            final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader")
                    .toString();
            final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString();

            final File keyspacesDirectory = new File(keyspaceDirectory);
            LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists());

            final File[] keyspaces = keyspacesDirectory.listFiles();

            String libProcessAddress = System.getenv("LIBPROCESS_IP");
            libProcessAddress = StringUtils.isBlank(libProcessAddress)
                    ? InetAddress.getLocalHost().getHostAddress()
                    : libProcessAddress;

            for (File keyspace : keyspaces) {
                final File[] columnFamilies = keyspace.listFiles();

                final String keyspaceName = keyspace.getName();
                if (keyspaceName.equals(StorageUtil.SCHEMA_FILE))
                    continue;
                LOGGER.info("Going to bulk load keyspace: {}", keyspaceName);

                for (File columnFamily : columnFamilies) {
                    final String columnFamilyName = columnFamily.getName();
                    if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE))
                        continue;
                    LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);

                    final String columnFamilyPath = columnFamily.getAbsolutePath();
                    final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress,
                            "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml,
                            columnFamilyPath);
                    LOGGER.info("Executing command: {}", command);

                    final ProcessBuilder processBuilder = new ProcessBuilder(command);
                    processBuilder.redirectErrorStream(true);
                    Process process = processBuilder.start();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        LOGGER.info(line);
                    }

                    int exitCode = process.waitFor();
                    LOGGER.info("Command exit code: {}", exitCode);

                    // Send TASK_ERROR
                    if (exitCode != 0) {
                        final String errMessage = String.format("Error restoring snapshot. Exit code: %s",
                                (exitCode + ""));
                        LOGGER.error(errMessage);
                        sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage);
                    }

                    LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);
                }
                LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName);
            }
            // cleanup downloaded snapshot directory recursively.
            Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName());
            if (rootPath.toFile().exists()) {
                Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(Path::toFile).forEach(File::delete);
            }
        } else {
            // run nodetool refresh rather than SSTableLoader, as on performance test
            // I/O stream was pretty slow between mesos container processes
            final String localLocation = context.getLocalLocation();
            final List<String> keyspaces = cassandra.getNonSystemKeySpaces();
            for (String keyspace : keyspaces) {
                final String keySpaceDirPath = localLocation + "/" + keyspace;
                File keySpaceDir = new File(keySpaceDirPath);
                File[] cfNames = keySpaceDir
                        .listFiles((current, name) -> new File(current, name).isDirectory());
                for (File cfName : cfNames) {
                    String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-"));
                    cassandra.getProbe().loadNewSSTables(keyspace, columnFamily);
                    LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace,
                            columnFamily);
                }
            }
        }

        final String message = "Finished restoring snapshot";
        LOGGER.info(message);
        sendStatus(driver, Protos.TaskState.TASK_FINISHED, message);
    } catch (Throwable t) {
        // Send TASK_FAILED
        final String errorMessage = "Failed restoring snapshot. Reason: " + t;
        LOGGER.error(errorMessage, t);
        sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage);
    }
}

From source file:com.cloud.utils.net.NetUtils.java

public static String getHostName() {
    try {//  ww  w.  j a v a  2s  . c  om
        final InetAddress localAddr = InetAddress.getLocalHost();
        if (localAddr != null) {
            return localAddr.getHostName();
        }
    } catch (final UnknownHostException e) {
        s_logger.warn("UnknownHostException when trying to get host name. ", e);
    }
    return "localhost";
}

From source file:io.fabric8.camel.FabricComponent.java

protected String replaceAnyIpAddress(String uri) {
    String result = uri;//from  ww  w. j a v a2  s  .c  o m
    //TODO do we need to support the IPV6 ?
    if (uri.indexOf("0.0.0.0") > 0) {
        try {
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            result = uri.replace("0.0.0.0", hostAddress);
        } catch (UnknownHostException ex) {
            LOG.warn("Cannot find the local host name, due to {0}", ex);
        }
    }
    return result;
}

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

private String getComputerName() {
    String hostname = TfsTelemetryHelper.UNKNOWN;

    try {/*from w  w  w. j a va2  s .co m*/
        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:ws.argo.DemoWebClient.Browser.BrowserController.java

/**
 * Return the ip info of where the web host lives that supports the browser
 * app./*from w  ww  . j  a  v  a 2  s . co  m*/
 * 
 * @return the ip addr info
 * @throws UnknownHostException if something goes wrong
 */
@GET
@Path("/ipAddrInfo")
public String getIPAddrInfo() throws UnknownHostException {

    Properties clientProps = getPropeSenderProps();

    StringBuffer buf = new StringBuffer();

    InetAddress localhost = null;
    NetworkInterface ni = null;
    try {
        localhost = InetAddress.getLocalHost();
        LOGGER.debug("Network Interface name not specified.  Using the NI for localhost "
                + localhost.getHostAddress());
        ni = NetworkInterface.getByInetAddress(localhost);
    } catch (UnknownHostException | SocketException e) {
        LOGGER.error("Error occured dealing with network interface name lookup ", e);

    }

    buf.append("<p>").append("<span style='color: red'> IP Address: </span>")
            .append(localhost.getHostAddress());
    buf.append("<span style='color: red'> Host name: </span>").append(localhost.getCanonicalHostName());
    if (ni == null) {
        buf.append("<span style='color: red'> Network Interface is NULL </span>");
    } else {
        buf.append("<span style='color: red'> Network Interface name: </span>").append(ni.getDisplayName());
    }
    buf.append("</p><p>");
    buf.append("Sending probes to " + respondToAddresses.size() + " addresses -  ");
    for (ProbeRespondToAddress rta : respondToAddresses) {
        buf.append("<span style='color: red'> Probe to: </span>")
                .append(rta.respondToAddress + ":" + rta.respondToPort);
    }
    buf.append("</p>");

    return buf.toString();
}

From source file:net.phoenix.thrift.server.ZookeeperRegisterHandler.java

@Override
public void preServe() {
    log.info("start registering zookeeper to " + this.connectString);

    // ? serverName, IP?
    if (this.serverName == null) {
        InetAddress addr;// w ww.  j a v a  2 s .c  om
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            log.error("Unable to get current host name.");
            return;
        }
        this.serverName = addr.getHostAddress().toString();
    }

    // this.server = event.getRpcServer();
    try {
        this.prepareZookeeper();
    } catch (IOException ex) {
        log.error("Error in create zookeeper server instance.", ex);
        return;
    }
    try {
        this.createServiceNode();
    } catch (KeeperException ex) {
        log.error("Error in creating zookeeper service node.", ex);
        return;
    } catch (InterruptedException ex) {
        log.error("Error in creating zookeeper service node.", ex);
        return;
    }
    try {
        this.startService();
    } catch (KeeperException ex) {
        log.error("Error in starting zookeeper service.", ex);
        return;
    } catch (InterruptedException ex) {
        log.error("Error in starting zookeeper service.", ex);
        return;
    }
    this.stopped = false;
    log.info("Registered to zookeeper successfully, server name:" + this.serverName + ",service name:"
            + this.serviceName + ".");
}

From source file:it.anyplace.sync.core.configuration.ConfigurationService.java

private ConfigurationService(Properties properties) {
    deviceName = properties.getProperty(DEVICE_NAME);
    if (isBlank(deviceName)) {
        try {/*from   www  .  j  a  va 2 s.  c o m*/
            deviceName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ex) {
        }
        if (isBlank(deviceName) || equal(deviceName, "localhost")) {
            deviceName = "s-client";
        }
    }
    deviceId = properties.getProperty(DEVICE_ID);
    keystoreAlgo = properties.getProperty(KEYSTORE_ALGO);
    folders = Collections.synchronizedMap(Maps.<String, FolderInfo>newHashMap());
    String folderValue = properties.getProperty(FOLDERS);
    try {
        FolderConfigList folderConfigList = isBlank(folderValue) ? new FolderConfigList()
                : gson.fromJson(folderValue, FolderConfigList.class);
        for (FolderConfig folderConfig : folderConfigList.getFolders()) {
            folders.put(folderConfig.getFolder(),
                    new FolderInfo(folderConfig.getFolder(), folderConfig.getLabel()));
        }
    } catch (Exception ex) {
        logger.error("error reading folder field = " + folderValue, ex);
    }
    String keystoreValue = properties.getProperty(KEYSTORE);
    if (!Strings.isNullOrEmpty(keystoreValue)) {
        keystore = BaseEncoding.base64().decode(keystoreValue);
    }
    String cacheDir = properties.getProperty(CACHE);
    if (!isBlank(cacheDir)) {
        cache = new File(cacheDir);
    } else {
        cache = new File(System.getProperty("java.io.tmpdir"), "a_sync_client_cache");
    }
    cache.mkdirs();
    checkArgument(cache.isDirectory() && cache.canWrite(), "invalid cache dir = %s", cache);
    String tempDir = properties.getProperty(TEMP);
    if (!isBlank(tempDir)) {
        temp = new File(tempDir);
    } else {
        temp = new File(System.getProperty("java.io.tmpdir"), "a_sync_client_temp");
    }
    temp.mkdirs();
    checkArgument(temp.isDirectory() && temp.canWrite(), "invalid temp dir = %s", temp);
    String dbDir = properties.getProperty(DATABASE);
    if (!isBlank(dbDir)) {
        database = new File(dbDir);
    } else {
        database = new File(System.getProperty("user.home"), ".config/sclient/db");
    }
    database.mkdirs();
    checkArgument(database.isDirectory() && database.canWrite(), "invalid database dir = %s", database);
    peers = Collections.synchronizedMap(Maps.<String, DeviceInfo>newHashMap());
    String peersValue = properties.getProperty(PEERS);
    try {
        DeviceConfigList deviceConfigList = isBlank(peersValue) ? new DeviceConfigList()
                : gson.fromJson(peersValue, DeviceConfigList.class);
        for (DeviceConfig deviceConfig : deviceConfigList.getDevices()) {
            peers.put(deviceConfig.getDeviceId(),
                    new DeviceInfo(deviceConfig.getDeviceId(), deviceConfig.getName()));
        }
    } catch (Exception ex) {
        logger.error("error reading peers field = " + peersValue, ex);
    }
    String discoveryServerValue = properties.getProperty(DISCOVERY_SERVERS);
    discoveryServers = Strings.isNullOrEmpty(discoveryServerValue) ? Collections.<String>emptyList()
            : Arrays.asList(discoveryServerValue.split(","));
    clientVersion = MoreObjects.firstNonNull(emptyToNull(getClass().getPackage().getImplementationVersion()),
            "0.0.0");// version info from MANIFEST, with 'safe' default fallback
    String configurationValue = properties.getProperty(CONFIGURATION);
    if (!isBlank(configurationValue)) {
        configuration = new File(configurationValue);
    }
    repositoryH2Config = properties.getProperty(REPOSITORY_H2_CONFIG);
}

From source file:info.raack.appliancedetection.common.service.EmailErrorService.java

@PostConstruct
void init() {/*from w ww  .j a  v a  2  s. co m*/
    try {
        InetAddress addr = InetAddress.getLocalHost();
        // Get hostname
        hostname = addr.getHostName();
    } catch (UnknownHostException e) {
        hostname = "unknown";
    }
}