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.bitzeche.logging.gelfamqp4j.GelfAMQP4jAppender.java

private String getLocalHostName() {
    String hostName = null;//from ww  w. jav a 2 s.  co  m
    try {
        hostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        errorHandler.error("Unknown local hostname", e, ErrorCode.GENERIC_FAILURE);
    }

    return hostName;
}

From source file:com.edmunds.etm.client.impl.DaemonConfig.java

private static String getIpAddress() {
    try {//from  www .  j av  a2s  . co  m
        return InetAddress.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.genie.server.util.NetUtil.java

private static String getDCHostName() throws GenieException {
    LOG.debug("called");

    if (dcHostName != null && !dcHostName.isEmpty()) {
        return dcHostName;
    }//w w  w .  ja va 2s.  c om

    try {
        // gets the local instance hostname
        final InetAddress addr = InetAddress.getLocalHost();
        dcHostName = addr.getCanonicalHostName();
    } catch (final UnknownHostException e) {
        final String msg = "Unable to get the hostname";
        LOG.error(msg, e);
        throw new GenieServerException(msg, e);
    }

    return dcHostName;
}

From source file:de.cubeisland.engine.core.webapi.ApiServer.java

public ApiServer(Core core) {
    this.core = core;
    this.log = core.getLogFactory().getLog(Core.class, "WebAPI");
    this.log.addTarget(
            new AsyncFileTarget(LoggingUtil.getLogFile(core, "WebAPI"), LoggingUtil.getFileFormat(true, true),
                    true, LoggingUtil.getCycler(), core.getTaskManager().getThreadFactory()));
    this.log.addTarget(new LogProxyTarget(core.getLogFactory().getParent()));
    try {/*from   w  w  w  .  ja va 2s  .c o  m*/
        this.bindAddress.set(InetAddress.getLocalHost());
    } catch (UnknownHostException ignored) {
        this.log.warn("Failed to get the localhost!");
    }
}

From source file:org.manalith.ircbot.plugin.google.GooglePlugin.java

public String getGoogleTopResult(String keyword) {
    try {// w w w .  j  a  v  a 2s. c o m
        // http://code.google.com/apis/websearch/docs/#fonje
        final String url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0" //
                + "&q=" + keyword //
                + "&key=" + apiKey //
                + "&userip=" + InetAddress.getLocalHost().getHostAddress();

        MappingJackson2HttpMessageConverter conv = new MappingJackson2HttpMessageConverter();
        conv.setSupportedMediaTypes(
                Collections.singletonList(new MediaType("text", "javascript", Charset.forName("UTF-8"))));

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(conv);

        SearchResponse res = restTemplate.getForObject(url, SearchResponse.class);

        if (res.responseData != null && ArrayUtils.isNotEmpty(res.responseData.results)) {

            SearchResult result = res.responseData.results[0];

            // HTML  
            return result.content.replace("<b>", HIGH_INTENSITY).replace("</b>", LOW_INTENSITY)
                    .replace("&quot;", "\"").replace("&#39;", "'").replace("&gt;", ">").replace("&lt;", "<")
                    .replace("&amp;", "&").replace("\n", "") + " : " + result.unescapedUrl;
        }
    } catch (IOException e) {
        logger.warn(e.getMessage(), e);
    }

    return null;
}

From source file:Global.java

private Action<Void> getConfigSecretAction() {
    return new Action.Simple() {
        @Override/*from ww w  . j  a  va  2 s .c  o  m*/
        public Result call(Http.Context ctx) throws Throwable {
            if (ctx.request().method().toLowerCase().equals("post")) {
                Form<User> newSiteAdminUserForm = form(User.class).bindFromRequest();

                if (hasError(newSiteAdminUserForm)) {
                    return badRequest(secret.render(SiteAdmin.SITEADMIN_DEFAULT_LOGINID, newSiteAdminUserForm));
                }

                User siteAdmin = SiteAdmin.updateDefaultSiteAdmin(newSiteAdminUserForm.get());
                replaceSiteSecretKey(createSeed(siteAdmin.password));
                isRestartRequired = true;
                return ok(restart.render());
            } else {
                return ok(secret.render(SiteAdmin.SITEADMIN_DEFAULT_LOGINID, new Form<>(User.class)));
            }
        }

        private String createSeed(String basicSeed) {
            String seed = basicSeed;
            try {
                seed += InetAddress.getLocalHost();
            } catch (Exception e) {
                play.Logger.warn("Failed to get localhost address", e);
            }
            return seed;
        }

        private void replaceSiteSecretKey(String seed) throws IOException {
            SecureRandom random = new SecureRandom(seed.getBytes());
            String secret = new BigInteger(130, random).toString(32);

            Path path = Paths.get("conf/application.conf");
            byte[] bytes = Files.readAllBytes(path);
            String config = new String(bytes);
            config = config.replace(DEFAULT_SECRET, secret);
            Files.write(path, config.getBytes());
        }

        private boolean hasError(Form<User> newUserForm) {
            if (StringUtils.isBlank(newUserForm.field("loginId").value())) {
                newUserForm.reject("loginId", "user.wrongloginId.alert");
            }

            if (!newUserForm.field("loginId").value().equals("admin")) {
                newUserForm.reject("loginId", "user.wrongloginId.alert");
            }

            if (StringUtils.isBlank(newUserForm.field("password").value())) {
                newUserForm.reject("password", "user.wrongPassword.alert");
            }

            if (!newUserForm.field("password").value().equals(newUserForm.field("retypedPassword").value())) {
                newUserForm.reject("retypedPassword", "user.confirmPassword.alert");
            }

            if (StringUtils.isBlank(newUserForm.field("email").value())) {
                newUserForm.reject("email", "validation.invalidEmail");
            }

            if (User.isEmailExist(newUserForm.field("email").value())) {
                newUserForm.reject("email", "user.email.duplicate");
            }

            return newUserForm.hasErrors();
        }
    };
}

From source file:com.jagornet.dhcp.client.ClientSimulatorV4.java

/**
 * Instantiates a new test client.//from w  ww . j a v a  2 s.c o m
 *
 * @param args the args
 * @throws Exception the exception
 */
public ClientSimulatorV4(String[] args) throws Exception {
    DEFAULT_ADDR = InetAddress.getLocalHost();

    setupOptions();

    if (!parseOptions(args)) {
        formatter = new HelpFormatter();
        String cliName = this.getClass().getName();
        formatter.printHelp(cliName, options);
        System.exit(0);
    }

    try {
        start();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:adams.core.net.InternetHelper.java

/**
 * Returns the machine name of the local host as string.
 *
 * @return      the machine name, null if not available
 *//*from   w  w w  .  j a  va2s .  c om*/
public static synchronized String getLocalHostName() {
    String result;

    if (m_Hostname == null) {
        try {
            result = InetAddress.getLocalHost().getHostName();
        } catch (Exception e) {
            result = getHostnameFromNetworkInterface();
        }

        m_Hostname = result;
    } else {
        result = m_Hostname;
    }

    return result;
}

From source file:com.yahoo.ycsb.db.AbstractRiakClient.java

@Override
public void init() throws DBException {
    super.init();

    try {//from   w w  w.j ava2s .c  o m
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e1) {
        hostname = "localhost";
    }

    // Keep track of number of calls to init (for later cleanup)
    INIT_COUNT.incrementAndGet();

    // Synchronized so that we only have a single
    // cluster/session instance for all the threads.
    synchronized (INIT_COUNT) {

        if (config != null) {
            assert riakClient != null;
            return;
        }

        config = Config.create(getProperties());

        try {
            final RiakCluster riakCluster = config.createRiakCluster();
            riakCluster.start();

            riakClient = new RiakClient(riakCluster);
        } catch (UnknownHostException e) {
            throw new DBException("Can't create Riak Cluster", e);
        }

        debugPrint(
                "\n\n%s client has been initialized with the following configuration:\n"
                        + "\tHosts:        %s\n" + "\tDefault Port: %d\n" + "\tBucket type:  %s\n"
                        + "\tThread cnt:   %d\n" + "\tR Val:        %d\n" + "\tW Val:        %d\n"
                        + "\tRead Retry Count: %d\n\n",
                this.getClass().getSimpleName(), config.hosts, config.defaultPort, config.bucketType,
                config.threadCount, config.r_value, config.w_value, config.readRetryCount);
    }
}

From source file:ch.sdi.core.impl.ftp.FtpExecutorTest.java

/**
 * Test method for {@link ch.sdi.core.impl.ftp.FtpExecutor#executeUpload(java.io.InputStream, java.lang.String)}.
 */// w  w  w.j a v  a 2  s.  c  om
@Test
public void testInitBySpring() throws Throwable {
    myLog.debug("Testing self-initialize by Spring context");

    String targetDir = myTargetDirLocal;
    cleanTargetDir(targetDir);
    Map<String, InputStream> filesToUpload = createFileUploadMap(targetDir);

    TestUtils.addToEnvironment(myEnv, SdiMainProperties.KEY_FTP_CMD_LINE, "-A localhost");

    registerFtpUser("anonymous",
            System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName());

    FtpServer server = startFtpServer();
    try {
        // omit call to init in order to auto initialize by spring context
        myClassUnderTest.connectAndLogin();
        myClassUnderTest.uploadFiles(filesToUpload);
        myClassUnderTest.logoutAndDisconnect();
        assertFilesUploaded(createFileUploadMap(targetDir));
    } finally {
        if (server != null) {
            myLog.debug("stopping the embedded FTP server");
            server.stop();
        } // if myServer != null
    }
}