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.terracotta.management.entity.tms.TmsAgentTest.java

@Before
public void setUp() throws Exception {
    PassthroughServer activeServer = new PassthroughServer();
    activeServer.setServerName("server-1");
    activeServer.setBindPort(9510);//from   w  ww .  ja v a 2 s .  co m
    activeServer.setGroupPort(9610);
    activeServer.registerServerEntityService(new TmsAgentEntityServerService());
    activeServer.registerClientEntityService(new TmsAgentEntityClientService());
    activeServer.registerClientEntityService(new ManagementAgentEntityClientService());
    activeServer.registerServerEntityService(new ManagementAgentEntityServerService());
    stripeControl = new PassthroughClusterControl("server-1", activeServer);

    clientIdentifier = ClientIdentifier.create(
            Long.parseLong(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]),
            InetAddress.getLocalHost().getHostAddress(), "UNKNOWN", "uuid");

    expectedCluster = Cluster.create()
            .addStripe(Stripe.create("stripe-1")
                    .addServer(Server.create("server-1").setBindAddress("0.0.0.0").setBindPort(9510)
                            .setGroupPort(9610).setHostName("localhost").setStartTime(0).setActivateTime(0)
                            .setHostAddress("127.0.0.1").setVersion("Version Passthrough 5.0.0-SNAPSHOT")
                            .setBuildId("Build ID").setState(Server.State.ACTIVE)
                            .addServerEntity(ServerEntity.create(getClass().getSimpleName(),
                                    TmsAgentEntity.class.getName(), 1))))
            .addClient(Client.create(clientIdentifier).setHostName(InetAddress.getLocalHost().getHostName()));

    client = expectedCluster.getClients().values().iterator().next();
    connection = Connection.create("uuid",
            expectedCluster.getStripe("stripe-1").get().getServerByName("server-1").get(),
            Endpoint.create(InetAddress.getLocalHost().getHostAddress(), -1) // values set by passthrough system
    );
    client.addConnection(connection);

    assertTrue(connection.fetchServerEntity(getClass().getSimpleName(), TmsAgentConfig.ENTITY_TYPE));
}

From source file:acromusashi.kafka.log.producer.LinuxApacheLogProducer.java

/**
 * ????Log?Tail?//  w w  w  .  j  a  va  2  s .  c o m
 * 
 * @param configMap ?Map
 */
protected void startTailLog(Map<String, Object> configMap) {
    String tailCommand = configMap.get("tail.command").toString();
    String tailPath = configMap.get("tail.path").toString();
    String tailCommandStr = tailCommand + " " + tailPath;
    String kafkaTopic = configMap.get("kafka.topic").toString();
    String apacheLogFormat = configMap.get("apachelog.format").toString();
    String jsonDateFormat = configMap.get("jsondate.format").toString();

    String hostname = "defaultHost";

    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException ex) {
        logger.warn("HostName resolve failed. Use default. : default=" + hostname, ex);
    }

    ProducerConfig producerConfig = ProducerConfigConverter.convertToProducerConfig(configMap);

    logger.info("Producer starting. Command=" + tailCommandStr);

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    LinuxLogTailExecutor executor = new LinuxLogTailExecutor(tailCommandStr, kafkaTopic, apacheLogFormat,
            jsonDateFormat, hostname);
    executor.initialize(producerConfig);

    executorService.execute(executor);

    logger.info("Producer started");
}

From source file:com.pinterest.terrapin.server.TerrapinServerHandler.java

public void start() throws Exception {
    String zookeeperQuorum = TerrapinUtil.getZKQuorumFromConf(configuration);
    int thriftPort = configuration.getInt(Constants.THRIFT_PORT, Constants.DEFAULT_THRIFT_PORT);

    // Connect to Helix.
    this.helixManager = HelixManagerFactory.getZKHelixManager(
            configuration.getString(Constants.HELIX_CLUSTER, Constants.HELIX_CLUSTER_NAME_DEFAULT),
            TerrapinUtil.getHelixInstanceFromHDFSHost(InetAddress.getLocalHost().getHostName()),
            InstanceType.PARTICIPANT, zookeeperQuorum);
    StateMachineEngine stateMach = this.helixManager.getStateMachineEngine();

    // Create state model factory for HDFS.
    Configuration conf = new Configuration();
    conf.set("fs.default.name", configuration.getString(Constants.HDFS_NAMENODE));
    // Setup HDFS short circuit parameters.
    conf.setBoolean("dfs.client.read.shortcircuit", true);
    conf.setInt("dfs.client.read.shortcircuit.streams.cache.size", 5000);
    conf.setInt("dfs.client.read.shortcircuit.buffer.size", 131072);
    conf.set("dfs.domain.socket.path", "/var/run/hadoop-hdfs/dn._PORT");

    FileSystem fs = FileSystem.get(conf);
    this.stateModelFactory = new OnlineOfflineStateModelFactory(this.configuration, resourcePartitionMap,
            new ReaderFactory(configuration, new HFileSystem(fs)));
    stateMach.registerStateModelFactory("OnlineOffline", this.stateModelFactory);
    this.helixManager.connect();

    // Start up the thrift server for serving.
    startThriftServer(thriftPort);//  w  w w  .j a  v a  2  s .  co m
}

From source file:info.sugoiapps.xoclient.XOverClient.java

/**
 * Get the internal IP address of the client machine.
 * @return the address//from   ww w  .j  ava2s .  c o  m
 */
private static String getLocalAddress() {
    InetAddress addr;
    try {
        addr = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        return "No address found";
    }
    return addr.getHostAddress();
}

From source file:jeeves.utils.EMail.java

/** Sends the message to the mail server
  *//*from w w  w .  j a v  a2  s.c  om*/

public boolean send() throws IOException {
    Socket socket = new Socket(sMailServer, iPort);
    try {
        in = new BufferedReader(new InputStreamReader(new DataInputStream(socket.getInputStream()),
                Charset.forName(Jeeves.ENCODING)));
        out = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream()), "ISO-8859-1");

        if (lookMailServer())
            if (sendData("2", "HELO " + InetAddress.getLocalHost().getHostName() + "\r\n"))
                if (sendData("2", "MAIL FROM: <" + sFrom + ">\r\n"))
                    if (sendData("2", "RCPT TO: <" + sTo + ">\r\n"))
                        if (sendData("354", "DATA\r\n"))
                            if (sendData("2", buildContent()))
                                if (sendData("2", "QUIT\r\n"))
                                    return true;

        sendData("2", "QUIT\r\n");
    } finally {
        IOUtils.closeQuietly(socket);
    }
    return false;
}

From source file:com.jmstoolkit.pipeline.AbstractPlugin.java

/**
 * Configures and starts the JMS MessageConsumer.
 *///  w w w  .  j ava  2s.c  om
@Override
public void init() {
    try {
        setConnection(getJmsTemplate().getConnectionFactory().createConnection());
        setSession(getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE));
        setConsumer(getSession().createConsumer(getInput()));
        getConsumer().setMessageListener(this);
        getConnection().start();

        System.setProperty(P_APP_NAME, APP_NAME);
        try {
            System.setProperty(P_HOSTNAME, InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            LOGGER.log(Level.WARNING, "Couldn't determine hostname", e);
            System.setProperty(P_HOSTNAME, D_HOSTNAME);
        }
    } catch (JMSException ex) {
        LOGGER.log(Level.SEVERE, "Failed to start MessageConsumer", ex);
        setStatus(STATUS_FAILED);
    }
}

From source file:com.nridge.connector.ws.con_ws.restlet.RestletApplication.java

/**
 * Returns a Restlet instance used to identify inbound requests for the
 * web service endpoints./*from w  w w.jav a2  s .  c  om*/
 *
 * @return Restlet instance.
 */
@Override
public Restlet createInboundRoot() {
    Restlet restletRoot;
    Logger appLogger = mAppMgr.getLogger(this, "createInboundRoot");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Context restletContext = getContext();
    Router restletRouter = new Router(restletContext);

    String propertyName = "restlet.host_names";
    String hostNames = mAppMgr.getString(propertyName);
    if (StringUtils.isEmpty(hostNames)) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();

            routerAttachEndPoints(restletRouter, "localhost");
            routerAttachEndPoints(restletRouter, inetAddress.getHostName());
            routerAttachEndPoints(restletRouter, inetAddress.getHostAddress());
            routerAttachEndPoints(restletRouter, inetAddress.getCanonicalHostName());
        } catch (UnknownHostException e) {
            appLogger.error(e.getMessage(), e);
            routerAttachEndPoints(restletRouter, "localhost");
        }
    } else {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] hostNameList = mAppMgr.getStringArray(propertyName);
            for (String hostName : hostNameList)
                routerAttachEndPoints(restletRouter, hostName);
        }
    }

    RestletFilter restletFilter = new RestletFilter(mAppMgr, restletContext);
    propertyName = "restlet.allow_addresses";
    String allowAddresses = mAppMgr.getString(propertyName);
    if (StringUtils.isNotEmpty(allowAddresses)) {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] allowAddressList = mAppMgr.getStringArray(propertyName);
            for (String allowAddress : allowAddressList) {
                restletFilter.add(allowAddress);
                appLogger.debug("Filter Allow Address: " + allowAddress);
            }
        } else {
            restletFilter.add(allowAddresses);
            appLogger.debug("Filter Allow Address: " + allowAddresses);
        }
        restletFilter.setNext(restletRouter);
        restletRoot = restletFilter;
    } else
        restletRoot = restletRouter;

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return restletRoot;
}

From source file:dk.netarkivet.viewerproxy.WebProxyTester.java

@After
public void tearDown() {
    if (proxy != null) {
        proxy.kill();/*from   w  w w.  ja  v a  2  s. com*/
    }
    // Check port not in use (since this might break later tests)
    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
        fail("Port still in use after killing server");
    } catch (IOException e) {
        // expected
    }
}

From source file:brooklyn.test.TestHttpServer.java

private InetAddress getLocalAddress() {
    try {/*from   w  w w.  j  av  a 2 s . c  o m*/
        return InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw Exceptions.propagate(e);
    }
}

From source file:info.magnolia.init.DefaultMagnoliaInitPaths.java

/**
 * Figures out the local host name, makes sure it's lowercase, and use its unqualified name if the {@value #MAGNOLIA_UNQUALIFIED_SERVER_NAME} init parameter is set to true.
 *//*from w w  w.j  a  va  2s  .  c o m*/
protected String determineServerName(ServletContext context) {
    final boolean unqualifiedServerName = BooleanUtils
            .toBoolean(context.getInitParameter(MAGNOLIA_UNQUALIFIED_SERVER_NAME));
    final String retroCompatMethodCall = magnoliaServletContextListener.initServername(unqualifiedServerName);
    if (retroCompatMethodCall != null) {
        DeprecationUtil.isDeprecated(
                "You should update your code and override determineServerName(ServletContext) instead of initServername(String)");
        return retroCompatMethodCall;
    }

    try {
        String serverName = StringUtils.lowerCase(InetAddress.getLocalHost().getHostName());

        if (unqualifiedServerName && StringUtils.contains(serverName, ".")) {
            serverName = StringUtils.substringBefore(serverName, ".");
        }
        return serverName;
    } catch (UnknownHostException e) {
        log.error(e.getMessage());
        return null;
    }
}