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.limegroup.gnutella.gui.DaapManager.java

/**
 * Starts the DAAP Server//from   w  w w.  j a  va 2  s  .co  m
 */
public synchronized void start() throws IOException {

    if (!isServerRunning()) {

        try {

            InetAddress addr = InetAddress.getLocalHost();

            if (addr.isLoopbackAddress() || !(addr instanceof Inet4Address)) {
                addr = null;
                Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
                if (interfaces != null) {
                    while (addr == null && interfaces.hasMoreElements()) {
                        NetworkInterface nif = (NetworkInterface) interfaces.nextElement();
                        Enumeration addresses = nif.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            InetAddress address = (InetAddress) addresses.nextElement();
                            if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                                addr = address;
                                break;
                            }
                        }
                    }
                }
            }

            if (addr == null) {
                stop();
                // No valid IP address -- just ignore, since
                // it's probably the user isn't connected to the
                // internet.  Next time they start, it might work.
                return;
            }

            rendezvous = new RendezvousService(addr);

            map = new SongURNMap();

            maxPlaylistSize = DaapSettings.DAAP_MAX_LIBRARY_SIZE.getValue();

            String name = DaapSettings.DAAP_LIBRARY_NAME.getValue();
            int revisions = DaapSettings.DAAP_LIBRARY_REVISIONS.getValue();
            boolean useLibraryGC = DaapSettings.DAAP_LIBRARY_GC.getValue();
            library = new Library(name, revisions, useLibraryGC);

            database = new Database(name);
            whatsNew = new Playlist(GUIMediator.getStringResource("SEARCH_TYPE_WHATSNEW"));
            creativecommons = new Playlist(GUIMediator.getStringResource("LICENSE_CC"));
            videos = new Playlist(GUIMediator.getStringResource("MEDIA_VIDEO"));

            Transaction txn = library.open(false);
            library.add(txn, database);
            database.add(txn, creativecommons);
            database.add(txn, whatsNew);
            database.add(txn, videos);
            creativecommons.setSmartPlaylist(txn, true);
            whatsNew.setSmartPlaylist(txn, true);
            videos.setSmartPlaylist(txn, true);
            txn.commit();

            LimeConfig config = new LimeConfig(addr);

            final boolean NIO = DaapSettings.DAAP_USE_NIO.getValue();

            server = DaapServerFactory.createServer(library, config, NIO);

            server.setAuthenticator(new LimeAuthenticator());
            server.setStreamSource(new LimeStreamSource());
            server.setFilter(new LimeFilter());

            if (!NIO) {
                server.setThreadFactory(new LimeThreadFactory());
            }

            final int maxAttempts = 10;

            for (int i = 0; i < maxAttempts; i++) {
                try {
                    server.bind();
                    break;
                } catch (BindException bindErr) {
                    if (i < (maxAttempts - 1)) {
                        // try next port...
                        config.nextPort();
                    } else {
                        throw bindErr;
                    }
                }
            }

            Thread serverThread = new ManagedThread(server, "DaapServerThread") {
                protected void managedRun() {
                    try {
                        super.managedRun();
                    } catch (Throwable t) {
                        DaapManager.this.stop();
                        if (!handleError(t)) {
                            GUIMediator.showError("ERROR_DAAP_RUN_ERROR");
                            DaapSettings.DAAP_ENABLED.setValue(false);
                            if (t instanceof RuntimeException)
                                throw (RuntimeException) t;
                            throw new RuntimeException(t);
                        }
                    }
                }
            };

            serverThread.setDaemon(true);
            serverThread.start();

            rendezvous.registerService();

        } catch (IOException err) {
            stop();
            throw err;
        }
    }
}

From source file:com.envirover.spl.SPLDaemon.java

@Override
public void start() throws Exception {
    String ip = InetAddress.getLocalHost().getHostAddress();
    System.out.printf("Starting RockBLOCK HTTP message handler on http://%s:%d%s...", ip,
            config.getRockblockPort(), config.getHttpContext());
    System.out.println();//from   ww w.  ja  v a  2 s.c o m

    httpServer.start();
    mtMsgPumpThread.start();
    tcpServer.start();
    wsServer.start();

    Thread.sleep(1000);

    logger.info("SPL Ground Control server started.");
}

From source file:com.jagornet.dhcpv6.client.TestV4Client.java

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

    setupOptions();

    if (!parseOptions(args)) {
        formatter = new HelpFormatter();
        String cliName = this.getClass().getName();
        formatter.printHelp(cliName, options);
        //            PrintWriter stderr = new PrintWriter(System.err, true);   // auto-flush=true
        //            formatter.printHelp(stderr, 80, cliName, null, options, 2, 2, null);
        System.exit(0);
    }

    try {
        start();

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

From source file:com.baifendian.swordfish.execserver.ExecThriftServer.java

public ExecThriftServer() throws TTransportException, UnknownHostException {
    masterDao = DaoFactory.getDaoInstance(MasterDao.class);
    masterServer = masterDao.getMasterServer();

    if (masterServer == null) {
        logger.error("Can't found master server");
        throw new RuntimeException("can't found master server");
    }/*from w w  w.j av  a2  s.  co  m*/

    masterClient = new MasterClient(masterServer.getHost(), masterServer.getPort(),
            Constants.defaultThriftRpcRetrites);

    // executor ?, ??
    host = InetAddress.getLocalHost().getHostAddress();
    port = conf.getInt(Constants.EXECUTOR_PORT, 10000);
}

From source file:clientpaxos.ClientPaxos.java

public static void ParseCommand(String msg) throws Exception {
    if (!voteInput) {
        if (msg.equals("join")) {
            String json;/*from   ww w  . j  a va2  s. c om*/
            JSONObject jsonObject = new JSONObject();
            System.out.print("Masukkan nama : ");
            String username = scan.nextLine();
            jsonObject.put("method", "join");
            jsonObject.put("username", username);
            jsonObject.put("udp_address", InetAddress.getLocalHost().getHostAddress());
            host = InetAddress.getLocalHost().getHostAddress();
            System.out.print("Masukkan port : ");
            port = scan.nextInt();
            scan.nextLine();
            jsonObject.put("udp_port", port);
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        } else if (msg.equals("leave")) {
            String json;
            player_id = -1;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "leave");
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        } else if (msg.equals("ready")) {
            String json;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", "ready");
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        } else if (msg.equals("client_address")) {
            getClientAddress();
        } else if (msg.equals("prepare")) {
            UDPThread.propose();
        } else {
            String json;
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method", msg);
            json = jsonObject.toString();
            System.out.println("Send to server : " + json);
            sendToServer(json);
        }
    } else {
        Vote(msg);
    }
}

From source file:MailTest.java

/**
 * Sends the mail message that has been authored in the GUI.
 */// w  w w.jav  a2 s  .c  om
public void sendMail() {
    try {
        Socket s = new Socket(smtpServer.getText(), 25);

        InputStream inStream = s.getInputStream();
        OutputStream outStream = s.getOutputStream();

        in = new Scanner(inStream);
        out = new PrintWriter(outStream, true /* autoFlush */);

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

        receive();
        send("HELO " + hostName);
        receive();
        send("MAIL FROM: <" + from.getText() + ">");
        receive();
        send("RCPT TO: <" + to.getText() + ">");
        receive();
        send("DATA");
        receive();
        send(message.getText());
        send(".");
        receive();
        s.close();
    } catch (IOException e) {
        comm.append("Error: " + e);
    }
}

From source file:gobblin.runtime.util.JobMetrics.java

/**
 *
 * Builds the clusterIdentifier tag.//from w w  w  .j  a va  2 s.c o m
 *
 * <p><b>MapReduce mode</b>
 * Gets the value for "yarn.resourcemanager.address" from {@link Configuration} excluding the port number.
 * If "yarn.resourcemanager.address" is not set, (possible in Hadoop1), falls back to "mapreduce.jobtracker.address"</p>
 *
 *<p><b>Standalone mode (outside of hadoop)</b>
 * returns the Hostname of {@link InetAddress#getLocalHost()}</p>
 *
 */
public static String getClusterIdentifierTag() {

    // ResourceManager address in Hadoop2
    String clusterIdentifier = HADOOP_CONFIGURATION.get("yarn.resourcemanager.address");

    // If job is running on Hadoop1 use jobtracker address
    if (clusterIdentifier == null) {
        clusterIdentifier = HADOOP_CONFIGURATION.get("mapreduce.jobtracker.address");
    }

    clusterIdentifier = ClustersNames.getInstance().getClusterName(clusterIdentifier);

    // If job is running outside of Hadoop (Standalone) use hostname
    // If clusterIdentifier is localhost or 0.0.0.0 use hostname
    if (clusterIdentifier == null || StringUtils.startsWithIgnoreCase(clusterIdentifier, "localhost")
            || StringUtils.startsWithIgnoreCase(clusterIdentifier, "0.0.0.0")) {
        try {
            clusterIdentifier = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            // Do nothing. Tag will not be generated
        }
    }

    return clusterIdentifier;

}

From source file:com.jcraft.weirdx.XDMCP.java

void getLocalHost(String name) {
    myaddress = new byte[4];
    try {//from   w  w w  . ja  v a2s  .  c o  m
        InetAddress local;
        if (name != null && name.length() > 0) {
            local = InetAddress.getByName(name);
        } else {
            local = InetAddress.getLocalHost();
        }
        byte[] b = local.getHostAddress().getBytes();
        int bi = 0;
        for (int i = 0; i < 4; i++) {
            myaddress[i] = 0;
            while (bi < b.length && b[bi] != '.') {
                myaddress[i] = (byte) (myaddress[i] * 10 + (b[bi] - '0'));
                bi++;
            }
            if (b.length <= bi)
                break;
            bi++;
        }
    } catch (Exception e) {
        LOG.error(e);
    }
}

From source file:org.wso2.am.integration.tests.other.APIMANAGER5326CustomStatusMsgTestCase.java

@Test(groups = "wso2.am", description = "testing error responses")
public void testAPIErrorResponse() throws Exception {

    //Login to the API Publisher
    org.wso2.carbon.automation.test.utils.http.client.HttpResponse response;
    response = apiPublisher.login(user.getUserName(), user.getPassword());
    verifyResponse(response);// www . ja  v a2 s. c  o m

    String apiName = "ErrorResponseCheckAPI";
    String apiVersion = "1.0.0";
    String apiContext = "message";
    String endpointUrl = "http://" + InetAddress.getLocalHost().getHostName() + ":1989";
    String appName = "testApplication";

    try {
        //Create the api creation request object
        APIRequest apiRequest;
        apiRequest = new APIRequest(apiName, apiContext, new URL(endpointUrl));

        apiRequest.setVersion(apiVersion);
        apiRequest.setTiersCollection(APIMIntegrationConstants.API_TIER.UNLIMITED);
        apiRequest.setTier(APIMIntegrationConstants.API_TIER.UNLIMITED);

        //Add the API using the API publisher.
        response = apiPublisher.addAPI(apiRequest);
        verifyResponse(response);

        APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(apiName, user.getUserName(),
                APILifeCycleState.PUBLISHED);
        //Publish the API
        response = apiPublisher.changeAPILifeCycleStatus(updateRequest);
        verifyResponse(response);

        //Login to the API Store
        response = apiStore.login(user.getUserName(), user.getPassword());
        verifyResponse(response);

        //Add an Application in the Store.
        response = apiStore.addApplication(appName, APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, "",
                "");
        verifyResponse(response);

        //Subscribe the API to the DefaultApplication
        SubscriptionRequest subscriptionRequest = new SubscriptionRequest(apiName, apiVersion,
                user.getUserName(), appName, APIMIntegrationConstants.API_TIER.UNLIMITED);
        response = apiStore.subscribe(subscriptionRequest);
        verifyResponse(response);

        //Generate production token and invoke with that
        APPKeyRequestGenerator generateAppKeyRequest = new APPKeyRequestGenerator(appName);
        String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData();
        JSONObject responseJson = new JSONObject(responseString);

        //Get the accessToken which was generated.
        String accessToken = responseJson.getJSONObject("data").getJSONObject("key").getString("accessToken");

        //Going to access the API with the version in the request url.
        String apiInvocationUrl = getAPIInvocationURLHttp(apiContext, apiVersion);

        HttpClient httpclient = new DefaultHttpClient();
        HttpUriRequest getRequest1 = new HttpGet(apiInvocationUrl);
        getRequest1.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));

        waitForAPIDeploymentSync(apiRequest.getProvider(), apiRequest.getName(), apiRequest.getVersion(),
                APIMIntegrationConstants.IS_API_EXISTS);

        org.apache.http.HttpResponse httpResponse = httpclient.execute(getRequest1);
        Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 400, "Response Code Mismatched");
        Assert.assertEquals(httpResponse.getStatusLine().toString().contains("Custom response"), true,
                "Response received with Custom Status Message");

    } catch (APIManagerIntegrationTestException e) {
        log.error("APIManagerIntegrationTestException " + e.getMessage(), e);
        Assert.assertTrue(false);
    } catch (JSONException e) {
        log.error("Error parsing JSON to get access token " + e.getMessage(), e);
        Assert.assertTrue(false);
    } catch (XPathExpressionException e) {
        log.error("XPathExpressionException " + e.getMessage(), e);
        Assert.assertTrue(false);
    } catch (IOException e) {
        log.error("IOException " + e.getMessage(), e);
        Assert.assertTrue(false);
    }
}

From source file:edu.cornell.med.icb.R.RUtils.java

/**
 * Can be used to start a rserve instance.
 * @param threadPool The ExecutorService used to start the Rserve process
 * @param rServeCommand Full path to command used to start Rserve process
 * @param host Host where the command should be sent
 * @param port Port number where the command should be sent
 * @param username Username to send to the server if authentication is required
 * @param password Password to send to the server if authentication is required
 * @return The return value from the Rserve instance
 *//*from ww  w  .  j  av a  2s .  co  m*/
static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host,
        final int port, final String username, final String password) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Attempting to start Rserve on " + host + ":" + port);
    }

    return threadPool.submit(new Callable<Integer>() {
        public Integer call() throws IOException {
            final List<String> commands = new ArrayList<String>();

            // if the host is not local, use ssh to exec the command
            if (!"localhost".equals(host) && !"127.0.0.1".equals(host)
                    && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) {
                commands.add("ssh");
                commands.add(host);
            }

            // TODO - this will fail when spaces are in the the path to the executable
            CollectionUtils.addAll(commands, rServeCommand.split(" "));
            commands.add("--RS-port");
            commands.add(Integer.toString(port));

            final String[] command = commands.toArray(new String[commands.size()]);
            LOG.debug(ArrayUtils.toString(commands));

            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            final Process process = builder.start();
            BufferedReader br = null;
            try {
                final InputStream is = process.getInputStream();
                final InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(host + ":" + port + "> " + line);
                    }
                }

                process.waitFor();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Rserve on " + host + ":" + port + " terminated");
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted!", e);
                process.destroy();
                Thread.currentThread().interrupt();
            } finally {
                IOUtils.closeQuietly(br);
            }

            final int exitValue = process.exitValue();
            if (LOG.isInfoEnabled()) {
                LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue);
            }
            return exitValue;
        }
    });
}