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:de.ingrid.interfaces.csw.server.impl.GenericServer.java

@Override
public Document process(GetCapabilitiesRequest request, String variant) throws CSWException {

    final String documentKey = ConfigurationKeys.CAPABILITIES_DOC;

    Document doc = this.getDocument(documentKey, variant);

    // try to replace the interface URLs
    NodeList nodes = this.xpath.getNodeList(doc, "//ows:Operation/*/ows:HTTP/*/@xlink:href");
    // get host/* w  w w .  ja v a 2 s .c  o  m*/
    String host = ApplicationProperties.get(ConfigurationKeys.SERVER_INTERFACE_HOST, null);
    if (host == null) {
        log.info("The interface host address is not specified, use local hosts address instead.");
        try {
            InetAddress addr = InetAddress.getLocalHost();
            host = addr.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("Unable to get interface host address.", e);
            throw new RuntimeException("Unable to get interface host address.", e);
        }
    }
    // get the port (defaults to 80)
    String port = ApplicationProperties.get(ConfigurationKeys.SERVER_INTERFACE_PORT, "80");
    // get the port (defaults to 80)
    String path = ApplicationProperties.get(ConfigurationKeys.SERVER_INTERFACE_PATH, "80");
    // replace interface host and port
    for (int idx = 0; idx < nodes.getLength(); idx++) {
        String s = nodes.item(idx).getTextContent();
        s = s.replaceAll(ConfigurationKeys.VARIABLE_INTERFACE_HOST, host);
        s = s.replaceAll(ConfigurationKeys.VARIABLE_INTERFACE_PORT, port);
        s = s.replaceAll(ConfigurationKeys.VARIABLE_INTERFACE_PATH, path);
        nodes.item(idx).setTextContent(s);
    }

    return doc;
}

From source file:com.thoughtworks.go.server.util.GoSslSocketConnector.java

private String getHostname() {
    try {//from w  ww.  j  a va2 s.c o  m
        return InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        throw ExceptionUtils.bomb(e);
    }
}

From source file:com.at.lic.LicenseControl.java

private String getLicenseCheckCode() {
    String os_arch = getSysProp("os.arch"); // x86
    String os_name = getSysProp("os.name"); // Windows XP
    String os_version = getSysProp("os.version"); // 5.1
    String sun_arch_data_model = getSysProp("sun.arch.data.model"); // 32
    String user_language = getSysProp("user.language"); // zh
    String sun_cpu_isalist = getSysProp("sun.cpu.isalist"); // pentium_pro +
    // mmx//from  www  .  ja v  a 2s .  c om
    // pentium_pro
    // pentium+mmx
    // pentium i486
    // i386 i86

    String mac = null;
    InetAddress addr = null;

    try {
        mac = getMAC();
        addr = InetAddress.getLocalHost();
    } catch (Exception e) {
        log.error("Getting information from ethernet card failed.", e);
        die();
    }

    StringBuilder sb = new StringBuilder();
    sb.append(os_arch.hashCode());
    sb.append(os_name.hashCode());
    sb.append(os_version.hashCode());
    sb.append(sun_arch_data_model.hashCode());
    sb.append(user_language.hashCode());
    sb.append(sun_cpu_isalist.hashCode());
    sb.append(mac.hashCode());
    sb.append(addr.hashCode());

    int licCheckCode = sb.toString().hashCode();

    return String.valueOf(licCheckCode);
}

From source file:com.clearspring.metriccatcher.Loader.java

/**
 * Load properties, build a MetricCatcher, start catching
 *
 * @param propertiesFile The config file
 * @throws IOException if the properties file cannot be read
 *///from  w w  w  .j av  a 2  s  .  com
public Loader(File propertiesFile) throws IOException {
    logger.info("Starting metriccatcher");

    logger.info("Loading configuration from: " + propertiesFile.getAbsolutePath());
    Properties properties = new Properties();
    try {
        properties.load(new FileReader(propertiesFile));
        for (Object key : properties.keySet()) { // copy properties into system properties
            System.setProperty((String) key, (String) properties.get(key));
        }
    } catch (IOException e) {
        logger.error("error reading properties file: " + e);
        System.exit(1);
    }

    int reportingInterval = 60;
    String intervalProperty = properties.getProperty(METRICCATCHER_INTERVAL);
    if (intervalProperty != null) {
        try {
            reportingInterval = Integer.parseInt(intervalProperty);
        } catch (NumberFormatException e) {
            logger.warn("Couldn't parse " + METRICCATCHER_INTERVAL + " setting", e);
        }
    }

    boolean disableJvmMetrics = false;
    String disableJvmProperty = properties.getProperty(METRICCATCHER_DISABLE_JVM_METRICS);
    if (disableJvmProperty != null) {
        disableJvmMetrics = BooleanUtils.toBoolean(disableJvmProperty);
        if (disableJvmMetrics) {
            logger.info("Disabling JVM metric reporting");
        }
    }

    boolean reportingEnabled = false;
    // Start a Ganglia reporter if specified in the config
    String gangliaHost = properties.getProperty(METRICCATCHER_GANGLIA_HOST);
    String gangliaPort = properties.getProperty(METRICCATCHER_GANGLIA_PORT);
    if (gangliaHost != null && gangliaPort != null) {
        logger.info("Creating Ganglia reporter pointed at " + gangliaHost + ":" + gangliaPort);
        GangliaReporter gangliaReporter = new GangliaReporter(gangliaHost, Integer.parseInt(gangliaPort));
        gangliaReporter.printVMMetrics = !disableJvmMetrics;
        gangliaReporter.start(reportingInterval, TimeUnit.SECONDS);
        reportingEnabled = true;
    }

    // Start a Graphite reporter if specified in the config
    String graphiteHost = properties.getProperty(METRICCATCHER_GRAPHITE_HOST);
    String graphitePort = properties.getProperty(METRICCATCHER_GRAPHITE_PORT);
    if (graphiteHost != null && graphitePort != null) {
        String graphitePrefix = properties.getProperty(METRICCATCHER_GRAPHITE_PREFIX);
        if (graphitePrefix == null) {
            graphitePrefix = InetAddress.getLocalHost().getHostName();
        }
        logger.info("Creating Graphite reporter pointed at " + graphiteHost + ":" + graphitePort
                + " with prefix '" + graphitePrefix + "'");
        GraphiteReporter graphiteReporter = new GraphiteReporter(graphiteHost, Integer.parseInt(graphitePort),
                StringUtils.trimToNull(graphitePrefix));
        graphiteReporter.printVMMetrics = !disableJvmMetrics;
        graphiteReporter.start(reportingInterval, TimeUnit.SECONDS);
        reportingEnabled = true;
    }

    String reporterConfigFile = properties.getProperty(METRICCATCHER_REPORTER_CONFIG);
    if (reporterConfigFile != null) {
        logger.info("Trying to load reporterConfig from file: {}", reporterConfigFile);
        try {
            ReporterConfig.loadFromFileAndValidate(reporterConfigFile).enableAll();
        } catch (Exception e) {
            logger.error("Failed to load metrics-reporter-config, metric sinks will not be activated", e);
        }
        reportingEnabled = true;
    }

    if (!reportingEnabled) {
        logger.error("No reporters enabled.  MetricCatcher can not do it's job");
        throw new RuntimeException("No reporters enabled");
    }

    int maxMetrics = Integer.parseInt(properties.getProperty(METRICCATCHER_MAX_METRICS, "500"));
    logger.info("Max metrics: " + maxMetrics);
    Map<String, Metric> lruMap = new LRUMap<String, Metric>(10, maxMetrics);

    int port = Integer.parseInt(properties.getProperty(METRICCATCHER_UDP_PORT, "1420"));
    logger.info("Listening on UDP port " + port);
    DatagramSocket socket = new DatagramSocket(port);

    metricCatcher = new MetricCatcher(socket, lruMap);
    metricCatcher.start();

    // Register a shutdown hook and wait for termination
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            shutdown();
        };
    });
}

From source file:com.mirth.connect.connectors.tcp.TcpMessageReceiver.java

protected ServerSocket createSocket(URI uri) throws IOException {
    String host = uri.getHost();// ww w.j  ava2s  .  c  o m
    int backlog = connector.getBacklog();
    if (host == null || host.length() == 0) {
        host = "localhost";
    }
    InetAddress inetAddress = InetAddress.getByName(host);
    if (inetAddress.equals(InetAddress.getLocalHost()) || inetAddress.isLoopbackAddress()
            || host.trim().equals("localhost")) {
        return new ServerSocket(uri.getPort(), backlog);
    } else {
        return new ServerSocket(uri.getPort(), backlog, inetAddress);
    }
}

From source file:org.apache.nifi.processors.rt.DeviceRegistryReportingTask.java

private NiFiDevice populateNetworkingInfo(NiFiDevice device) {

    InetAddress ip;// w  w w .  j a v  a 2  s .  com
    try {

        ip = InetAddress.getLocalHost();

        NetworkInterface network = NetworkInterface.getByInetAddress(ip);

        //Check this isn't null
        if (network == null) {
            //Hail mary to try and get eth0
            getLogger().warn(
                    "Hardcoded getting network interface by ETH0 which could be the incorrect interface but others were null");
            network = NetworkInterface.getByName("eth0");
        }

        byte[] mac = network.getHardwareAddress();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < mac.length; i++) {
            sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
        }

        //Set the values to the device object.
        device.setDeviceId(sb.toString());
        device.setIp(ip.getHostAddress());

        String hostname = InetAddress.getLocalHost().getHostName();
        logger.error("First attempt at getting hostname: " + hostname);
        if (!StringUtils.isEmpty(hostname)) {
            device.setHostname(hostname);
        } else {
            //Try the linux approach ... could fail if hostname(1) system command is not available.
            try {
                Process process = Runtime.getRuntime().exec("hostname");
                InputStream is = process.getInputStream();

                StringWriter writer = new StringWriter();
                IOUtils.copy(is, writer, "UTF-8");
                hostname = writer.toString();
                if (StringUtils.isEmpty(hostname)) {
                    device.setHostname("UNKNOWN");
                } else {
                    device.setHostname(hostname);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
                logger.error("Error attempting to resolve hostname", ex);
            }
        }

    } catch (UnknownHostException e) {
        e.printStackTrace();
        logger.error("Unknown host exception getting hostname", e);
    } catch (SocketException e) {
        e.printStackTrace();
        logger.error("socket exception getting hostname", e);
    }

    return device;
}

From source file:com.cloudera.flume.handlers.hdfs.CustomDfsSink.java

public CustomDfsSink(String path, OutputFormat format, Event event, String hiveTableName) {
    sb = new StringBuilder();

    Preconditions.checkArgument(path != null);
    Preconditions.checkArgument(format != null);
    this.path = path;
    this.localEvent = event;

    cal = Calendar.getInstance();
    cal.setTimeInMillis(localEvent.getTimestamp());
    this.format = format;
    this.writer = null;
    this.conf = FlumeConfiguration.get();
    this.hiveMarkerFolder = conf.getHiveDefaultMarkerFolder();

    if (StringUtils.isNotBlank(hiveTableName)) {
        this.hiveOutput = true;
        this.hiveTableName = hiveTableName;
        hup = new MarkerStore(hiveTableName, null, false);
    }//from  ww w .ja va 2 s  .c  o m

    try {
        machineHostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        LOG.error("Error getting hostname for local machine: " + e.getMessage());
    }
}

From source file:com.flipkart.flux.guice.module.ContainerModule.java

/**
 * Creates the Jetty server instance for the Flux API endpoint.
 * @param port where the service is available.
 * @return Jetty Server instance/*  www.  ja va 2s.  com*/
 */
@Named("APIJettyServer")
@Provides
@Singleton
Server getAPIJettyServer(@Named("Api.service.port") int port,
        @Named("APIResourceConfig") ResourceConfig resourceConfig, ObjectMapper objectMapper)
        throws URISyntaxException, UnknownHostException {
    //todo-ashish figure out some way of setting acceptor/worker threads
    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    provider.setMapper(objectMapper);
    resourceConfig.register(provider);
    final Server server = JettyHttpContainerFactory.createServer(UriBuilder
            .fromUri(
                    "http://" + InetAddress.getLocalHost().getHostAddress() + RuntimeConstants.API_CONTEXT_PATH)
            .port(port).build(), resourceConfig);
    server.setStopAtShutdown(true);
    return server;
}

From source file:com.summit.jbeacon.beacons.MultiCastResourceBeacon.java

public void startListening() throws MultiCastResourceBeaconException {
    try {/*w w w  . java  2 s.  c  o  m*/
        if (hostName == null) {
            hostName = InetAddress.getLocalHost().getHostName();
        }
        listeningSocket = new ServerSocket();
        listeningSocket.setReuseAddress(true);
        listeningSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), getListenPort()), 0);

        if (ip == null) {
            ip = listeningSocket.getInetAddress().getHostAddress();
        }

        listenerThread = new MultiCastResourceListener(listeningSocket);
        new Thread(listenerThread).start();
    } catch (IOException ex) {
        throw new MultiCastResourceBeaconException(ex.getMessage(), ex);
    }
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static String getBootStrapHostFromML() {
    InputStream jstream = null;//from   w ww.  j ava2s.c o m
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet("http://localhost:8002/manage/v2/properties?format=json");
        HttpResponse resp = client.execute(getrequest);
        jstream = resp.getEntity().getContent();
        JsonNode jnode = new ObjectMapper().readTree(jstream);
        String propName = "bootstrap-host";
        if (!jnode.isNull()) {

            if (jnode.has(propName)) {
                System.out.println("Bootstrap Host: "
                        + jnode.withArray(propName).get(0).get("bootstrap-host-name").asText());
                return jnode.withArray(propName).get(0).get("bootstrap-host-name").asText();
            } else {
                System.out.println("Missing " + propName
                        + " field from properties end point so sending java conanical host name\n"
                        + jnode.toString());
                return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
            }
        } else {
            System.out.println("Rest endpoint returns empty stream");
            return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
        }

    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();

        return "localhost";
    } finally {
        jstream = null;
    }
}