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.manalith.ircbot.plugin.google.GooglePlugin.java

private int getGoogleCount(String keyword) {
    try {// w w w. j a  v a 2s.  c  om
        // http://code.google.com/apis/websearch/docs/#fonje
        URL url = new URL("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&" + "q="
                + URLEncoder.encode(keyword, "UTF-8") + "&key=" + apiKey + "&userip="
                + InetAddress.getLocalHost().getHostAddress());
        URLConnection connection = url.openConnection();
        connection.addRequestProperty("Referer", apiReferer);

        String line;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }

        return Integer.parseInt(new JSONObject(builder.toString()).getJSONObject("responseData")
                .getJSONObject("cursor").getString("estimatedResultCount"));

    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } catch (JSONException e) {
        logger.error(e.getMessage(), e);
    }

    return -1;

}

From source file:io.hops.metadata.util.DistributedRTClientEvaluation.java

public DistributedRTClientEvaluation(String rtAddress, int nbSimulatedNM, int hbPeriod, long duration,
        String output, int startingPort, int nbNMTotal)
        throws IOException, YarnException, InterruptedException {

    this.nbNM = nbSimulatedNM;
    this.hbPeriod = hbPeriod;
    this.duration = duration;
    this.output = output;
    this.nbNMTotal = nbNMTotal;
    conf = new YarnConfiguration();
    conf.setStrings(YarnConfiguration.RM_RESOURCE_TRACKER_ADDRESS, rtAddress);
    conf.setClass(YarnConfiguration.RM_SCHEDULER, FifoScheduler.class, ResourceScheduler.class);

    //Create NMs//from w  w w  .j a v a2 s . co m
    for (int i = 0; i < nbSimulatedNM; i++) {
        nmMap.put(i, NodeId.newInstance(InetAddress.getLocalHost().getHostName(), startingPort + i));
    }

    start();
}

From source file:com.googlecode.jsendnsca.MessagePayload.java

/**
 * Set the hostname in the passive check
 *
 * @param useCanonical true to use this machines fully qualified domain name, false
 *                     to use the short hostname
 *///w  w  w.j  a  v  a  2  s.c  o  m
public void setHostname(boolean useCanonical) {
    InetAddress ipAddress;
    try {
        ipAddress = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new UnknownHostRuntimeException(e);
    }
    if (useCanonical) {
        this.hostname = ipAddress.getCanonicalHostName();
    } else {
        this.hostname = ipAddress.getHostName();
    }
}

From source file:org.devgateway.toolkit.forms.service.DerbyDatabaseBackupService.java

/**
 * Gets the URL (directory/file) of the backupPath. Adds as prefixes the
 * last leaf of backup's location parent directory + {@link #databaseName}
 * If the backupPath does not have a parent, it uses the host name from
 * {@link InetAddress#getLocalHost()}/*from  www .j  av  a2 s .c  o  m*/
 * 
 * @param backupPath
 *            the parent directory for the backup
 * @return the backup url to be used by the backup procedure
 * @throws UnknownHostException
 */
private String createBackupURL(final String backupPath) {
    java.text.SimpleDateFormat todaysDate = new java.text.SimpleDateFormat("yyyyMMdd-HHmmss");
    String parent = null;
    Path originalPath = Paths.get(backupPath);
    Path filePath = originalPath.getFileName();
    if (filePath != null) {
        parent = filePath.toString();
    } else {
        try {
            // fall back to hostname instead
            parent = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            LOGGER.debug("Cannot get localhost/hostname! " + e);
            return null;
        }
    }

    String backupURL = backupPath + "/" + parent + "-" + databaseName + "-"
            + todaysDate.format((java.util.Calendar.getInstance()).getTime());
    return backupURL;
}

From source file:ch.epfl.eagle.daemon.nodemonitor.NodeMonitorThrift.java

/**
 * Initialize this thrift service./*w  w  w . ja  v  a 2 s  .c o  m*/
 *
 * This spawns 2 multi-threaded thrift servers, one exposing the app-facing
 * agent service and the other exposing the internal-facing agent service,
 * and listens for requests to both servers. We require explicit specification of the
 * ports for these respective interfaces, since they cannot always be determined from
 * within this class under certain configurations (e.g. a config file specifies
 * multiple NodeMonitors).
 */
public void initialize(Configuration conf, int nmPort, int internalPort) throws IOException {
    nodeMonitor.initialize(conf, internalPort);

    // Setup application-facing agent service.
    NodeMonitorService.Processor<NodeMonitorService.Iface> processor = new NodeMonitorService.Processor<NodeMonitorService.Iface>(
            this);

    int threads = conf.getInt(EagleConf.NM_THRIFT_THREADS, DEFAULT_NM_THRIFT_THREADS);
    TServers.launchThreadedThriftServer(nmPort, threads, processor);

    // Setup internal-facing agent service.
    InternalService.Processor<InternalService.Iface> internalProcessor = new InternalService.Processor<InternalService.Iface>(
            this);
    int internalThreads = conf.getInt(EagleConf.INTERNAL_THRIFT_THREADS, DEFAULT_INTERNAL_THRIFT_THREADS);
    TServers.launchThreadedThriftServer(internalPort, internalThreads, internalProcessor);

    internalAddr = new InetSocketAddress(InetAddress.getLocalHost(), internalPort);
}

From source file:net.dfs.remote.main.ClientServicesStarter.java

public static String clientIP() throws UnknownHostException {
    return InetAddress.getLocalHost().getHostAddress();
}

From source file:com.zotoh.maedr.device.HttpIOTrait.java

/**
 * @return//from w w  w.ja  va 2 s . c  o m
 * @throws UnknownHostException
 */
public InetAddress getIP() throws UnknownHostException {
    return isEmpty(_host) ? InetAddress.getLocalHost() : InetAddress.getByName(_host);
}

From source file:in.gov.uidai.auth.aua.httpclient.BfdClient.java

public BfdResponseDetails performBfd(Bfd bfd) {
    try {// w w  w . j a  v a2s.  co  m
        String signedXML = generateSignedBfdXML(bfd);
        System.out.println(signedXML);

        String uriString = bfdServerURI.toString() + (bfdServerURI.toString().endsWith("/") ? "" : "/")
                + bfd.getAc() + "/" + bfd.getUid().charAt(0) + "/" + bfd.getUid().charAt(1);

        if (StringUtils.isNotBlank(asaLicenseKey)) {
            uriString = uriString + "/" + asaLicenseKey;
        }

        URI authServiceURI = new URI(uriString);

        WebResource webResource = Client.create(HttpClientHelper.getClientConfig(bfdServerURI.getScheme()))
                .resource(authServiceURI);

        String responseXML = webResource.header("REMOTE_ADDR", InetAddress.getLocalHost().getHostAddress())
                .post(String.class, signedXML);

        System.out.println(responseXML);

        return new BfdResponseDetails(responseXML, parseBfdResponseXML(responseXML));

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception during authentication " + e.getMessage(), e);
    }
}

From source file:org.apache.hyracks.http.test.HttpServerTest.java

@Test
public void testMalformedString() throws Exception {
    WebManager webMgr = new WebManager();
    HttpServer server = new HttpServer(webMgr.getBosses(), webMgr.getWorkers(), PORT, NUM_EXECUTOR_THREADS,
            SERVER_QUEUE_SIZE);// w ww  . j ava2s  .  c om
    SlowServlet servlet = new SlowServlet(server.ctx(), new String[] { PATH });
    server.addServlet(servlet);
    webMgr.add(server);
    webMgr.start();
    try {
        StringBuilder response = new StringBuilder();
        try (Socket s = new Socket(InetAddress.getLocalHost(), PORT)) {
            PrintWriter pw = new PrintWriter(s.getOutputStream());
            pw.println("GET /?handle=%7B%22handle%22%3A%5B0%2C%200%5D%7 HTTP/1.1");
            pw.println("Host: 127.0.0.1");
            pw.println();
            pw.flush();
            BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line).append('\n');
            }
            br.close();
        }
        String output = response.toString();
        Assert.assertTrue(output.contains(HttpResponseStatus.BAD_REQUEST.toString()));
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        webMgr.stop();
    }
}

From source file:de.codecentric.batch.configuration.MetricsExporterConfiguration.java

private String getShortHostname() {
    try {/*w w  w. jav a 2s . co m*/
        String hostname = InetAddress.getLocalHost().getHostName();
        if (hostname.indexOf('.') > 0) {
            hostname = hostname.substring(0, hostname.indexOf('.'));
        }
        return hostname;
    } catch (UnknownHostException e) {
        return "unknown";
    }
}