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:org.dawnsci.commandserver.core.process.ProgressableProcess.java

public ProgressableProcess(final URI uri, final String statusTName, final String statusQName, StatusBean bean) {

    this.uri = uri;
    this.statusTName = statusTName;
    this.statusQName = statusQName;
    this.bean = bean;
    this.broadcaster = new Broadcaster(uri, statusQName, statusTName);
    bean.setStatus(Status.QUEUED);// www  .j  a v a 2s  . c o  m
    try {
        bean.setHostName(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        // Not fatal but would be nice...
        e.printStackTrace();
    }
    broadcast(bean);
}

From source file:org.motechproject.metrics.impl.StatsdAgentBackendImpl.java

public StatsdAgentBackendImpl() {
    try {/*from  ww w  .  j ava 2  s.c  o  m*/
        hostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        // This is ok it just means host specific metrics will not be published
        //log.error("Unable to get local hostname", e);
    }
}

From source file:de.dakror.virtualhub.server.Server.java

public Server() {
    currentServer = this;

    dir = new File(CFG.DIR, "Server");
    dir.mkdir();/*from w ww .  ja v a2s. c o  m*/

    frame = new ServerFrame();
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            shutdown();
        }
    });

    setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            frame.log("ERROR: " + sw.toString());
        }
    });

    try {
        socket = new ServerSocket(CFG.SERVER_PORT, 0, InetAddress.getLocalHost());
        frame.log("Starte Server unter " + socket.getInetAddress().getHostAddress() + ":"
                + socket.getLocalPort());
    } catch (BindException e) {
        frame.log("Es luft bereits ein Server auf diesem Port!");
        shutdown();
        return;
    } catch (Exception e) {
        e.printStackTrace();
    }

    DBManager.init();
    frame.log("Datenbank initialisiert");

    start();
}

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

@Override
public void start() {
    super.start();
    EventBus eb = vertx.eventBus();//from w  ww  .j  av  a 2 s.  com

    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:org.devtcg.five.util.streaming.LocalHttpServer.java

public void bind(int port) throws IOException {
    bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
}

From source file:com.twitter.heron.metricscachemgr.MetricsCacheManager.java

public static void main(String[] args) throws Exception {
    Options options = constructOptions();
    Options helpOptions = constructHelpOptions();

    CommandLineParser parser = new DefaultParser();

    // parse the help options first.
    CommandLine cmd = parser.parse(helpOptions, args, true);
    if (cmd.hasOption("h")) {
        usage(options);//from  w  w  w . j  av a2 s.c  o  m
        return;
    }

    try {
        // Now parse the required options
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        usage(options);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    Level logLevel = Level.INFO;
    if (cmd.hasOption("v")) {
        logLevel = Level.ALL;
    }

    String cluster = cmd.getOptionValue("cluster");
    String role = cmd.getOptionValue("role");
    String environ = cmd.getOptionValue("environment");
    int masterPort = Integer.valueOf(cmd.getOptionValue("master_port"));
    int statsPort = Integer.valueOf(cmd.getOptionValue("stats_port"));
    String systemConfigFilename = cmd.getOptionValue("system_config_file");
    String overrideConfigFilename = cmd.getOptionValue("override_config_file");
    String metricsSinksConfigFilename = cmd.getOptionValue("sink_config_file");
    String topologyName = cmd.getOptionValue("topology_name");
    String topologyId = cmd.getOptionValue("topology_id");
    String metricsCacheMgrId = cmd.getOptionValue("metricscache_id");

    // read heron internal config file
    SystemConfig systemConfig = SystemConfig.newBuilder(true).putAll(systemConfigFilename, true)
            .putAll(overrideConfigFilename, true).build();

    // Log to file and sink(exception)
    LoggingHelper.loggerInit(logLevel, true);
    LoggingHelper.addLoggingHandler(
            LoggingHelper.getFileHandler(metricsCacheMgrId, systemConfig.getHeronLoggingDirectory(), true,
                    systemConfig.getHeronLoggingMaximumSize(), systemConfig.getHeronLoggingMaximumFiles()));
    LoggingHelper.addLoggingHandler(new ErrorReportLoggingHandler());

    LOG.info(String.format(
            "Starting MetricsCache for topology %s with topologyId %s with "
                    + "MetricsCache Id %s, master port: %d.",
            topologyName, topologyId, metricsCacheMgrId, masterPort));

    LOG.info("System Config: " + systemConfig);

    // read sink config file
    MetricsSinksConfig sinksConfig = new MetricsSinksConfig(metricsSinksConfigFilename);
    LOG.info("Sinks Config: " + sinksConfig.toString());

    // build config from cli
    Config config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig())
            .putAll(Config.newBuilder().put(Key.CLUSTER, cluster).put(Key.ROLE, role).put(Key.ENVIRON, environ)
                    .build())
            .putAll(Config.newBuilder().put(Key.TOPOLOGY_NAME, topologyName).put(Key.TOPOLOGY_ID, topologyId)
                    .build())
            .build());
    LOG.info("Cli Config: " + config.toString());

    // build metricsCache location
    TopologyMaster.MetricsCacheLocation metricsCacheLocation = TopologyMaster.MetricsCacheLocation.newBuilder()
            .setTopologyName(topologyName).setTopologyId(topologyId)
            .setHost(InetAddress.getLocalHost().getHostName()).setControllerPort(-1) // not used for metricscache
            .setMasterPort(masterPort).setStatsPort(statsPort).build();

    MetricsCacheManager metricsCacheManager = new MetricsCacheManager(topologyName, METRICS_CACHE_HOST,
            masterPort, statsPort, systemConfig, sinksConfig, config, metricsCacheLocation);
    metricsCacheManager.start();

    LOG.info("Loops terminated. MetricsCache Manager exits.");
}

From source file:org.qi4j.library.shiro.StrictX509Test.java

@Override
protected void configureJetty(Server jetty) throws Exception {
    InetAddress lo = InetAddress.getLocalHost();
    int sslPort = findFreePortOnIfaceWithPreference(lo, 8443);
    httpHost = new HttpHost(lo.getHostAddress(), sslPort, "https");

    SslSelectChannelConnector sslConnector = new SslSelectChannelConnector();
    sslConnector.setPort(httpHost.getPort());
    sslConnector.setNeedClientAuth(true);
    sslConnector.setSslContext(X509FixturesData.serverSSLContext());
    sslConnector.setAllowRenegotiate(false);

    jetty.addConnector(sslConnector);//from w  w w  .  j ava 2 s.  c o m
}

From source file:net.firejack.platform.installation.processor.InstallSlaveProcessor.java

@Override
public void onApplicationEvent(InstallSlaveEvent event) {
    File keystore = InstallUtils.getKeyStore();

    String url = OpenFlameConfig.MASTER_URL.getValue();
    String admin = OpenFlameConfig.APP_ADMIN_NAME.getValue();
    String password = OpenFlameConfig.APP_ADMIN_PASSWORD.getValue();

    try {//w w  w .  java  2  s .c o m
        if (keystore.exists()) {
            X500Name info = KeyUtils.getInfo(keystore);
            url = info.getDomain();
        }

        String hostName = InetAddress.getLocalHost().getHostName();

        KeyPair keyPair = KeyUtils.generate(keystore);

        if (keyPair == null) {
            throw new IllegalStateException("Key not found");
        }

        X509Certificate certificate = KeyUtils.generateCertificate(url, 1, keyPair);

        if (StringUtils.isBlank(password)) {
            String cert = new String(Base64.encode(certificate.getEncoded()));
            OPFEngine.init(url, OpenFlame.PACKAGE, hostName, cert);
        } else {
            OPFEngine.init(url, admin, password);
        }

        ServerNodeConfig config = new ServerNodeConfig();

        config.setServerName(hostName);
        //         config.setServerName(hostName + "_slave"); //TODO [CLUSTER] don't commit this line
        config.setHost(InetAddress.getLocalHost().getHostAddress());
        config.setPort(Integer.decode(OpenFlameConfig.PORT.getValue()));
        config.setNodeType(ServerNodeType.OPF_SLAVE);
        config.setLookup(OpenFlame.PACKAGE);
        config.setCert(certificate.getEncoded());

        InputStream stream = OPFEngine.RegistryService.registerSlaveNode(config);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        IOUtils.copy(stream, output);
        byte[] decrypted = KeyUtils.decrypt(keyPair.getPrivate(), output.toByteArray());

        Map<String, String> map = EnvironmentsUtils.convertFromXml(new ByteArrayInputStream(decrypted));
        ConfigContainer.putAll(map);

        source.refreshDBProperties();
        OPFEngine.release();

        KeyUtils.add(keystore, keyPair, url);
        FileUtils.deleteQuietly(InstallUtils.getPropEnv());
    } catch (Exception e) {
        logger.error(e);
        throw new IllegalStateException(e);
    }

    OPFEngine.initialize();
}

From source file:com.zz.cluster4spring.localinfo.DefaultLocalNetworkInfoProvider.java

public String getLocalHostAddress() throws UnknownHostException {
    InetAddress localHost = InetAddress.getLocalHost();
    String result = localHost.getHostAddress();
    return result;
}

From source file:com.bt.aloha.sipp.SippEngineTestHelper.java

private void init() throws UnknownHostException {
    hostAddress = InetAddress.getLocalHost().getHostAddress();
    activeSippEngins.add(this);
    errSB = new StringBuffer();
}