Example usage for java.net InetAddress getByName

List of usage examples for java.net InetAddress getByName

Introduction

In this page you can find the example usage for java.net InetAddress getByName.

Prototype

public static InetAddress getByName(String host) throws UnknownHostException 

Source Link

Document

Determines the IP address of a host, given the host's name.

Usage

From source file:org.esigate.extension.http.DNS.java

@Override
public void init(Driver driver, Properties properties) {
    Collection<String> ips = REMOTE_IP.getValue(properties);

    if (ips.isEmpty()) {
        LOG.error("Missing configuration properties for driver {}. Property {}",
                driver.getConfiguration().getInstanceName(), REMOTE_IP.getName());
    } else {//from   www. j a  v  a2 s. c  o m
        String[] remoteURLS = Parameters.REMOTE_URL_BASE.getValue(properties);
        List<InetAddress> inetAddresses = new ArrayList<>();
        CustomizableDNSResolver customizableDNSResolver = new CustomizableDNSResolver();
        dnsResolver = customizableDNSResolver;
        for (String ip : ips) {
            try {
                inetAddresses.add(InetAddress.getByName(ip));
            } catch (UnknownHostException e) {
                LOG.error("Unable to resolve InetAddress [{}]", ip, e);
            }
        }

        for (String remoteURL : remoteURLS) {

            HttpHost host = UriUtils.extractHost(remoteURL);
            customizableDNSResolver.add(host.getHostName(), inetAddresses.toArray(new InetAddress[] {}));
        }

        driver.getEventManager().register(EventManager.EVENT_HTTP_BUILDER_INITIALIZATION, this);
    }
}

From source file:io.gravitee.reporter.elastic.spring.factory.ElasticClientFactory.java

private Client createTransportClient() {
    Settings settings = Settings.settingsBuilder().put("cluster.name", configuration.getClusterName()).build();
    TransportClient transportClient = TransportClient.builder().settings(settings).build();

    List<HostAddress> adresses = configuration.getHostsAddresses();

    for (HostAddress address : adresses) {
        try {/*w  w  w  .  ja v  a  2s  .  c om*/
            transportClient.addTransportAddress(new InetSocketTransportAddress(
                    InetAddress.getByName(address.getHostname()), address.getPort()));
        } catch (UnknownHostException uhe) {
            LOGGER.error("Error while creating transport client for Elastic", uhe);
        }
    }

    return transportClient;
}

From source file:com.googlecode.jsonrpc4j.spring.CompositeJsonStreamServiceExporter.java

/**
 * {@inheritDoc}/* w  ww. ja v a 2  s. c  o  m*/
 */
protected void exportService() throws Exception {

    // export
    // create a stream server if needed
    if (streamServer == null) {

        // make sure we have a factory
        if (serverSocketFactory == null) {
            serverSocketFactory = ServerSocketFactory.getDefault();
        }

        // create server socket
        ServerSocket serverSocket = serverSocketFactory.createServerSocket(port, backlog,
                InetAddress.getByName(hostName));

        // create the stream server
        streamServer = new StreamServer(getJsonRpcServer(), maxThreads, serverSocket);
        streamServer.setMaxClientErrors(maxClientErrors);
    }

    // start it
    streamServer.start();
}

From source file:com.intellij.plugins.firstspirit.languagesupport.FirstSpiritClassPathHack.java

public void addFirstSpiritClientJar(UrlClassLoader classLoader, HttpScheme schema, String serverName, int port,
        String firstSpiritUserName, String firstSpiritUserPassword) throws Exception {
    System.out.println("starting to download fs-client.jar");

    String resolvalbleAddress = null;

    // asking DNS for IP Address, if some error occur choose the given value from user
    try {//from ww  w .  j ava  2  s  .  c o m
        InetAddress address = InetAddress.getByName(serverName);
        resolvalbleAddress = address.getHostAddress();
        System.out.println("Resolved address: " + resolvalbleAddress);
    } catch (Exception e) {
        System.err.println("DNS cannot resolve address, using your given value: " + serverName);
        resolvalbleAddress = serverName;
    }

    String uri = schema + "://" + resolvalbleAddress + ":" + port + "/clientjar/fs-client.jar";
    String versionUri = schema + "://" + resolvalbleAddress + ":" + port + "/version.txt";
    String tempDirectory = System.getProperty("java.io.tmpdir");

    System.out.println(uri);
    System.out.println(versionUri);

    HttpClient client = new HttpClient();
    HttpMethod getVersion = new GetMethod(versionUri);
    client.executeMethod(getVersion);
    String currentServerVersionString = getVersion.getResponseBodyAsString();
    System.out
            .println("FirstSpirit server you want to connect to is at version: " + currentServerVersionString);

    File fsClientJar = new File(tempDirectory, "fs-client-" + currentServerVersionString + ".jar");

    if (!fsClientJar.exists()) {
        // get an authentication cookie from FirstSpirit
        HttpMethod post = new PostMethod(uri);
        post.setQueryString("login.user=" + URLEncoder.encode(firstSpiritUserName, "UTF-8") + "&login.password="
                + URLEncoder.encode(firstSpiritUserPassword, "UTF-8") + "&login=webnonsso");
        client.executeMethod(post);
        String setCookieJsession = post.getResponseHeader("Set-Cookie").getValue();

        // download the fs-client.jar by using the authentication cookie
        HttpMethod get = new GetMethod(uri);
        get.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        get.setRequestHeader("Cookie", setCookieJsession);
        client.executeMethod(get);

        InputStream inputStream = get.getResponseBodyAsStream();
        FileOutputStream outputStream = new FileOutputStream(fsClientJar);
        outputStream.write(IOUtils.readFully(inputStream, -1, false));
        outputStream.close();
        System.out.println("tempfile of fs-client.jar created within path: " + fsClientJar);
    }

    addFile(classLoader, fsClientJar);
}

From source file:org.apache.ftpserver.config.spring.SpringConfigTest.java

public void test() throws Throwable {
    XmlBeanFactory factory = new XmlBeanFactory(
            new FileSystemResource("src/test/resources/spring-config/config-spring-1.xml"));

    DefaultFtpServer server = (DefaultFtpServer) factory.getBean("server");

    assertEquals(500, server.getConnectionConfig().getMaxLogins());
    assertEquals(false, server.getConnectionConfig().isAnonymousLoginEnabled());
    assertEquals(123, server.getConnectionConfig().getMaxAnonymousLogins());
    assertEquals(124, server.getConnectionConfig().getMaxLoginFailures());
    assertEquals(125, server.getConnectionConfig().getLoginFailureDelay());

    Map<String, Listener> listeners = server.getServerContext().getListeners();
    assertEquals(3, listeners.size());/*from w w  w. jav  a2 s .  com*/

    Listener listener = listeners.get("listener0");
    assertNotNull(listener);
    assertTrue(listener instanceof NioListener);
    assertEquals(2222, ((NioListener) listener).getPort());
    assertEquals(InetAddress.getByName("1.2.3.4"),
            InetAddress.getByName(((NioListener) listener).getServerAddress()));
    assertEquals(100, ((NioListener) listener).getDataConnectionConfiguration().getIdleTime());
    assertTrue(((NioListener) listener).getDataConnectionConfiguration().isActiveEnabled());
    assertTrue(((NioListener) listener).getDataConnectionConfiguration().isImplicitSsl());

    assertEquals(InetAddress.getByName("1.2.3.4"), InetAddress
            .getByName(((NioListener) listener).getDataConnectionConfiguration().getActiveLocalAddress()));
    assertEquals("123-125", ((NioListener) listener).getDataConnectionConfiguration().getPassivePorts());
    assertEquals(false, ((NioListener) listener).getDataConnectionConfiguration().isPassiveIpCheck());

    RemoteIpFilter filter = (RemoteIpFilter) listener.getSessionFilter();
    assertEquals(3, filter.size());
    assertTrue(filter.contains(new Subnet(InetAddress.getByName("1.2.3.0"), 16)));
    assertTrue(filter.contains(new Subnet(InetAddress.getByName("1.2.4.0"), 16)));
    assertTrue(filter.contains(new Subnet(InetAddress.getByName("1.2.3.4"), 32)));
    listener = listeners.get("listener1");
    assertNotNull(listener);
    assertTrue(listener instanceof MyCustomListener);
    assertEquals(2223, listener.getPort());

    listener = listeners.get("listener2");
    assertNotNull(listener);
    assertTrue(listener instanceof MyCustomListener);
    assertEquals(2224, listener.getPort());

    CommandFactory cf = server.getCommandFactory();
    assertTrue(cf.getCommand("FOO") instanceof HELP);
    assertTrue(cf.getCommand("FOO2") instanceof STAT);

    List<String> languages = server.getServerContext().getMessageResource().getAvailableLanguages();

    assertEquals(2, languages.size());
    assertEquals("en", languages.get(0));
    assertEquals("zh-tw", languages.get(1));

    NativeFileSystemFactory fs = (NativeFileSystemFactory) server.getFileSystem();
    assertTrue(fs.isCreateHome());
    assertTrue(fs.isCaseInsensitive());

    assertEquals(2, server.getFtplets().size());
    assertEquals(123, ((TestFtplet) server.getFtplets().get("ftplet1")).getFoo());
    assertEquals(223, ((TestFtplet) server.getFtplets().get("ftplet2")).getFoo());
}

From source file:com.seajas.search.utilities.rmi.RestrictedHostSocketFactory.java

/**
 * Create a server socket which only binds to the specified hostname.
 * /*from ww w  .jav a 2s. c o m*/
 * @param port
 * @return ServerSocket
 * @throws IOException
 */
@Override
public ServerSocket createServerSocket(final int port) throws IOException {
    InetAddress inetAddress = null;

    if (logger.isInfoEnabled())
        logger.info(
                "Creating (server-side) socket #" + totalSocketsCreated.incrementAndGet() + " on port " + port);

    if (!StringUtils.isEmpty(hostname) && !hostname.equals("0.0.0.0"))
        inetAddress = InetAddress.getByName(hostname);

    ServerSocket result = new ServerSocket(port, DEFAULT_BACKLOG, inetAddress);

    result.setReuseAddress(true);

    return result;
}

From source file:edu.hawaii.soest.pacioos.text.MockDataSource.java

/**
 * Implements the Runnable interface, and creates a local data source server by
 * binding to the 127.0.0.1:5111 address.  Upon a client connection, sends all lines
 * of the mock data file to the client./*from w w  w.  j  a v  a  2s  .  c o  m*/
 * @see java.lang.Runnable#run()
 */
public void run() {
    String host = "127.0.0.1";
    int portNumber = 5111;
    clientSocket = null;
    InetAddress address = null;
    try {
        address = InetAddress.getByName(host);
        serverSocket = new ServerSocket(portNumber, 1, address);
        log.info("Accepting connections on " + serverSocket.getInetAddress() + ":"
                + serverSocket.getLocalPort());
        clientSocket = serverSocket.accept();

    } catch (IOException ioe) {
        log.error("Couldn't open the server socket: " + ioe.getMessage());
    }

    File ctdData = new File(mockCTDData);
    List<String> lines = new ArrayList<String>();
    try {
        lines = FileUtils.readLines(ctdData);

    } catch (IOException e) {
        log.error("Couldn't read data file: " + e.getMessage());

    }

    try {
        if (this.clientSocket.isConnected()) {
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            // loop through the file and send each line over the wire
            for (String line : lines) {
                line = line + "\r\n";
                log.debug("Line bytes: " + new String(Hex.encodeHex(line.getBytes("US-ASCII"))));
                out.print(line);
                out.flush();
                Thread.sleep(500);
            }
            out.close();
        } else {
            log.debug("Client is not connected");
        }
    } catch (IOException e) {
        e.printStackTrace();

    } catch (InterruptedException e) {
        e.printStackTrace();

    }

}

From source file:sample.session.SessionDetailsFilter.java

String getGeoLocation(String remoteAddr) {
    try {/*  w  ww .  j  ava2s . c  om*/
        CityResponse city = this.reader.city(InetAddress.getByName(remoteAddr));
        String cityName = city.getCity().getName();
        String countryName = city.getCountry().getName();
        if (cityName == null && countryName == null) {
            return null;
        } else if (cityName == null) {
            return countryName;
        } else if (countryName == null) {
            return cityName;
        }
        return cityName + ", " + countryName;
    } catch (Exception e) {
        return UNKNOWN;

    }
}

From source file:net.jradius.handler.dhcp.DHCPPoolHandler.java

private AddressPool getDefaultPool() {
    if (_pool != null)
        return _pool;

    try {//from   w w w .  j  a  v  a2s .c  o m
        InetAddress[] dns = new InetAddress[1];
        dns[0] = InetAddress.getByName("10.1.0.1");

        _pool = new AddressPoolImpl();
        _pool.setNetwork(InetAddress.getByName("10.1.0.0"));
        _pool.setNetmask(InetAddress.getByName("255.255.0.0"));
        _pool.setRouter(InetAddress.getByName("10.1.0.1"));
        _pool.setLeaseTime(900);
        _pool.setDns(dns);

        if (cache == null) {
            cache = new Cache("ippool", 10000, true, false, _pool.getLeaseTime() + 60,
                    _pool.getLeaseTime() + 30);
            cacheManager.addCache(cache);
        }

        _pool.setLeases(cache);

        //pool.addOption(Attr_DHCPProxyAutoDiscovery.VSA_TYPE, wpadURL);
        return _pool;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}