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:keywhiz.cli.CommandExecutor.java

public void executeCommand() throws IOException {
    if (command == null) {
        if (config.version) {
            System.out.println("Version: " + APP_VERSION);
        } else {// ww w  . java 2  s. c om
            System.err.println("Must specify a command.");
            parentCommander.usage();
        }

        return;
    }

    URL url;
    if (config.url == null || config.url.isEmpty()) {
        url = new URL("https", InetAddress.getLocalHost().getHostName(), 4444, "");
    } else {
        url = new URL(config.url);
    }

    HttpHost host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    KeywhizClient client;
    OkHttpClient encapsulatedClient;

    try {
        List<HttpCookie> cookieList = ClientUtils.loadCookies(COOKIE_PATH);
        encapsulatedClient = ClientUtils.sslOkHttpClient(cookieList);
        client = new KeywhizClient(mapper, ClientUtils.hostBoundWrappedHttpClient(host, encapsulatedClient));

        // Try a simple get request to determine whether or not the cookies are still valid
        if (!client.isLoggedIn()) {
            throw new UnauthorizedException();
        }
    } catch (IOException e) {
        // Either could not find the cookie file, or the cookies were expired -- must login manually.
        encapsulatedClient = ClientUtils.sslOkHttpClient(ImmutableList.of());
        client = new KeywhizClient(mapper, ClientUtils.hostBoundWrappedHttpClient(host, encapsulatedClient));
        String password = ClientUtils.readPassword();
        client.login(USER_NAME.value(), password);
    }
    // Save/update the cookies if we logged in successfully
    ClientUtils.saveCookies((CookieManager) encapsulatedClient.getCookieHandler(), COOKIE_PATH);

    Printing printing = new Printing(client);

    Command cmd = Command.valueOf(command.toUpperCase().trim());
    switch (cmd) {
    case LIST:
        new ListAction((ListActionConfig) commands.get(command), client, printing).run();
        break;

    case DESCRIBE:
        new DescribeAction((DescribeActionConfig) commands.get(command), client, printing).run();
        break;

    case ADD:
        new AddAction((AddActionConfig) commands.get(command), client, mapper).run();
        break;

    case DELETE:
        new DeleteAction((DeleteActionConfig) commands.get(command), client).run();
        break;

    case ASSIGN:
        new AssignAction((AssignActionConfig) commands.get(command), client).run();
        break;

    case UNASSIGN:
        new UnassignAction((UnassignActionConfig) commands.get(command), client).run();
        break;

    case LOGIN:
        // User is already logged in at this point
        break;

    default:
        commander.usage();
    }
}

From source file:functionaltests.scilab.AbstractScilabTest.java

protected void init() throws Exception {

    sci_tb_home = new File(System.getProperty("pa.scilab.home")).getCanonicalFile();

    test_home = resourceToFile("PrepareTest.sci").getParentFile();

    credFile = new File(test_home, "demo.cred");

    localhost = InetAddress.getLocalHost().getHostName();

    schedURI = new URI(SchedulerTHelper.getLocalUrl());

    // delete all db files
    File[] dbJobFiles = new File(TMPDIR).listFiles(new FilenameFilter() {
        @Override/* w  ww .j  a v  a 2s  . c om*/
        public boolean accept(File dir, String name) {
            if (name.startsWith(AOScilabEnvironment.MIDDLEMAN_JOBS_FILE_NAME)) {
                return true;
            } else if (name.startsWith(ScilabTaskRepository.SCILAB_EMBEDDED_JOBS_FILE_NAME)) {
                return true;
                // TODO : change below the value to JobDB.DEFAULT_STATUS_FILENAME
            } else if (name.startsWith("SmartProxy")) {
                return true;
            }
            return false;
        }
    });

    for (File f : dbJobFiles) {
        try {
            System.out.println("Deleting " + f);
            f.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

From source file:com.indeed.imhotep.builder.tsv.KerberosUtils.java

@Nullable
private static String getCanonicalHostNameSafe() {
    try {/*w w  w. j a v  a 2  s  .  c  o m*/
        return InetAddress.getLocalHost().getCanonicalHostName();
    } catch (UnknownHostException e) {
        log.error("Unable to lookup hostname of machine " + e.getMessage());
        return null;
    }
}

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

@Before
public void setUp() throws IOException {
    // Check port not in use (since this will fail all tests)

    httpPort = Settings.getInt(CommonSettings.HTTP_PORT_NUMBER);
    if (httpPort < 1025 || httpPort > 65535) {
        fail("Port must be in the range 1025-65535, not " + httpPort);
    }/*w w w.jav a2 s. co  m*/
    try {
        new Socket(InetAddress.getLocalHost(), httpPort);
        fail("Port already in use before unit test");
    } catch (IOException e) {
        // Expected
    }

    uriResolverMock = mock(URIResolver.class);
    /*
            requestMock = mock(org.eclipse.jetty.server.Request.class);
            responseMock = mock(org.eclipse.jetty.server.Response.class);
    */
    requestMock = mock(org.mortbay.jetty.Request.class);
    responseMock = mock(org.mortbay.jetty.Response.class);

}

From source file:it.reply.orchestrator.controller.DeploymentController.java

/**
 * Get the orchestrator status info.//from  w w  w. jav a 2 s . c o  m
 * 
 * @return the orchestrator status info.
 */
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/info", method = RequestMethod.GET)
public DebugInformation getInfo() {
    DebugInformation info = new DebugInformation();
    info.setProjectVersion(projectVersion);
    info.setProjectRevision(projectRevision);
    info.setProjectTimestamp(projectTimestamp);

    String hostname;
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (Exception ex) {
        hostname = "-NOT AVAILABLE-";
    }
    info.setServerHostname(hostname);

    return info;
}

From source file:com.bmwcarit.barefoot.matcher.ServerTest.java

@Test
public void testServer() throws IOException, JSONException, InterruptedException, ParseException {
    Server server = new Server();
    InetAddress host = InetAddress.getLocalHost();
    Properties properties = new Properties();
    properties.load(new FileInputStream("config/server.properties"));
    int port = Integer.parseInt(properties.getProperty("server.port"));

    server.start();//from  w w w .  jav a2s .  c  o m
    {
        String json = new String(
                Files.readAllBytes(Paths.get(ServerTest.class.getResource("x0001-015.json").getPath())),
                Charset.defaultCharset());
        sendRequest(host, port, new JSONArray(json));
    }
    server.stop();
}

From source file:com.qpark.eip.core.spring.statistics.impl.AppUserStatisticsChannelAdapter.java

/**
 * Get the host name of the server./*from   www . ja va2  s. c o  m*/
 *
 * @return the host name or <code>null</code>.
 */
String getHostName() {
    if (this.hostName == null) {
        try {
            this.hostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
    return this.hostName;
}

From source file:com.ottogroup.bi.asap.node.server.AsapProcessingNodeServer.java

/**
 * @see io.dropwizard.Application#run(io.dropwizard.Configuration, io.dropwizard.setup.Environment)
 *///  w w w. ja  v  a2  s  .  c o m
public void run(AsapProcessingNodeConfiguration configuration, Environment environment) throws Exception {

    PropertyConfigurator.configure(configuration.getLog4jConfiguration());

    this.pipelineManager = new MicroPipelineManager(
            loadAndDeployApplicationRepository(configuration.getApplicationRepository()));
    environment.jersey().register(new PipelineResource(this.pipelineManager));

    this.resourceManagerClient = new AsapResourceManagerClient(configuration.getResourceManagerConfiguration());
    try {
        ProcessingNodeRegistrationResponse registrationResponse = this.resourceManagerClient
                .registerProcessingNode(InetAddress.getLocalHost().getHostName(),
                        configuration.getServicePort(), configuration.getAdminPort());
        if (registrationResponse == null) {
            logger.error(
                    "Failed to register processing node with remote resource manager. Error: no response received. Processing node operates in standalone mode");
        } else {
            if (registrationResponse.getState() != ProcessingNodeRegistrationState.OK)
                throw new RuntimeException(
                        "[error=" + registrationResponse.getState() + "] " + registrationResponse.getMessage());
        }
    } catch (RemoteClientConnectionFailedException e) {
        logger.error(
                "Failed to register processing node with remote resource manager. Error: no response received. Processing node operates in standalone mode");
    }
}

From source file:org.prx.prp.StreamProxy.java

public void init(MediaPlayer m, Context mContext) {
    try {//  www.j  av  a2  s  .c o  m
        this.m = m;
        this.mContext = mContext;
        socket = new ServerSocket(port, 0, InetAddress.getLocalHost());
        socket.setSoTimeout(5000);
        port = socket.getLocalPort();
        Log.d(getClass().getName(), "port " + port + " obtained");
    } catch (UnknownHostException e) {
        Log.e(getClass().getName(), "Error initializing server", e);
    } catch (IOException e) {
        Log.e(getClass().getName(), "Error initializing server", e);
    }
}