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.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);/*from  w ww  .jav a  2 s .c  om*/

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}

From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java

private static String getLocalHostName() throws InitializationException {
    try {/*  ww  w .  j ava2s .  c  o m*/
        return InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        throw new InitializationException("Unknown host name for NTLM proxy", e);
    }
}

From source file:net.sf.j2ep.responsehandlers.ResponseHandlerBase.java

/**
 * Will set the via header with this proxies data to the response.
 * @param response The response we set the header for
 *///from  w  w w .j a v  a  2s  . c o m
private void setViaHeader(HttpServletResponse response) {
    String serverHostName = "jEasyReverseProxy";
    try {
        serverHostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        LogFactory.getLog(RequestHandlerBase.class).error("Couldn't get the hostname needed for header Via", e);
    }

    Header originalVia = method.getResponseHeader("via");
    StringBuffer via = new StringBuffer("");
    if (originalVia != null) {
        via.append(originalVia.getValue()).append(", ");
    }
    via.append(method.getStatusLine().getHttpVersion()).append(" ").append(serverHostName);

    response.setHeader("via", via.toString());
}

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

public static InetAddress getLocalInetAddress() {
    try {//from w ww. j av  a2s.co m
        return InetAddress.getLocalHost();
    } catch (final UnknownHostException e) {
        s_logger.warn("UnknownHostException in getLocalInetAddress().", e);
        return null;
    }
}

From source file:org.trpr.platform.runtime.impl.bootstrap.spring.Bootstrap.java

/**
 * No args constructor/*from  w  ww. j a va  2  s  . c  o m*/
 */
public Bootstrap() {
    try {
        this.hostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        //ignore the exception, not critical information
    }
}

From source file:com.yahoo.ads.pb.PistachiosClient.java

public PistachiosClient() throws Exception {
    try {//  w  ww  .j a v a 2s  .  c  o  m
        helixPartitionSpectator = new HelixPartitionSpectator(conf.getString(ZOOKEEPER_SERVER), // zkAddr
                "PistachiosCluster", InetAddress.getLocalHost().getHostName() //conf.getString(PROFILE_HELIX_INSTANCE_ID) // instanceName
        );

    } catch (Exception e) {
        logger.error(
                "Error init HelixPartitionSpectator, are zookeeper and helix installed and configured correctly?",
                e);
        throw e;
    }

    localHostAddress = InetAddress.getLocalHost().getHostAddress();
}

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

public CustomDfsSink(String path, OutputFormat format, Event event) {

    Preconditions.checkArgument(path != null);
    Preconditions.checkArgument(format != null);
    this.path = path;
    this.format = format;
    this.writer = null;
    this.localEvent = event;
    cal = Calendar.getInstance();
    cal.setTimeInMillis(localEvent.getTimestamp());
    this.conf = FlumeConfiguration.get();
    try {/*from w ww .ja  v a 2 s.com*/
        machineHostName = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        LOG.error("Error getting hostname for local machine: " + e.getMessage());
    }

}

From source file:net.firejack.platform.model.config.GatewayLoader.java

/**
 * @param lookup/*from w  w w  .  j a  v  a 2 s.c om*/
 * @param port
 * @return
 */
public Environments getConfig(String lookup, Integer port) {
    processSiteMinderConfigs();
    try {
        File keystore = InstallUtils.getKeyStore();

        String url = Env.FIREJACK_URL.getValue();

        logger.info("Load config from: " + url);

        KeyPair keyPair = KeyUtils.generate(keystore);

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

        String name = InetAddress.getLocalHost().getHostName();
        X509Certificate certificate = KeyUtils.generateCertificate(url, 1, keyPair);

        String cert = new String(Base64.encode(certificate.getEncoded()));
        OPFEngine.init(url, lookup, name, cert);

        ServerNodeConfig config = new ServerNodeConfig();
        config.setServerName(name);
        config.setHost(InetAddress.getLocalHost().getHostAddress());
        config.setPort(port);
        config.setNodeType(ServerNodeType.GATEWAY);
        config.setLookup(lookup);
        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());

        return InstallUtils.deserialize(new ByteArrayInputStream(decrypted));
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:arena.utils.URLUtils.java

public static String getServerName() {
    String serverName = "localhost";
    try {//from   w w  w . ja  v a2s.  co  m
        InetAddress localhost = InetAddress.getLocalHost();
        serverName = localhost.getHostName();
    } catch (Throwable err) {
        LogFactory.getLog(URLUtils.class).error("Error looking up server name", err);
    }
    return serverName;
}

From source file:com.necla.simba.server.simbastore.Main.java

public void serve() {
    try {/* w  ww  .j  a va  2  s. c  om*/
        tables = new ConcurrentHashMap<String, SimbaTable>();
        objectStore = new SwiftHandler(properties);
        tableStore = new CassandraHandler(properties);
        transactions = new ConcurrentHashMap<Integer, SyncTransaction>();

        int threads = Integer.parseInt(properties.getProperty("thread.count"));

        queues = new LinkedBlockingQueue[threads];
        workerThreads = new Thread[threads];

        hasher = new ConsistentHash();

        gm = new GatewayManager(queues, properties);

        server = new SimbaStoreServer(InetAddress.getLocalHost(),
                Integer.parseInt(properties.getProperty("port")), queues, hasher, gm);

        subscriptionManager = new SubscriptionManager(server);

        for (int i = 0; i < threads; i++) {
            queues[i] = new LinkedBlockingQueue<ServerDataEvent>();

            SimbaStoreWorker worker = new SimbaStoreWorker(properties, queues[i], objectStore, tableStore,
                    tables, subscriptionManager, transactions, gm);

            worker.setSimbaServer(server);
            workerThreads[i] = new Thread(worker, Integer.toString(i));
            workerThreads[i].start();
        }

        new Thread(server, "server").start();

        gm.setServer(server);
        gm.start();

        LOG.debug("SimbaServer start-up complete.");

    } catch (IOException e) {
        LOG.error("Could not start SimbaServer: " + e.getMessage());
        System.exit(1);
    }

}