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:com.meltmedia.cadmium.cli.AbstractAuthorizedOnly.java

/**
 * Converts the passed in siteUrl to be https if not already or not local.
 * //  w  ww  .  jav  a 2s  .c o  m
 * @param siteUrl The url of a cadmium site.
 * @return The passed in siteUrl or the same url but converted to https.
 */
protected String getSecureBaseUrl(String siteUrl) {
    if (!siteUrl.startsWith("http://") && !siteUrl.startsWith("https://")) {
        siteUrl = "http://" + siteUrl;
    }
    Matcher urlMatcher = URL_PATTERN.matcher(siteUrl);
    if (urlMatcher.matches()) {
        logger.debug("Url matches [{}]", siteUrl);
        boolean local = false;
        try {
            logger.debug("Checking if host [{}] is local", urlMatcher.group(1));
            InetAddress hostAddr = InetAddress.getByName(urlMatcher.group(1));
            local = hostAddr.isLoopbackAddress() || hostAddr.isSiteLocalAddress();
            logger.debug("IpAddress [{}] local: {}", hostAddr.getHostAddress(), local);
        } catch (UnknownHostException e) {
            logger.warn("Hostname not found [" + siteUrl + "]", e);
        }
        if (!local) {
            return siteUrl.replaceFirst("http://", "https://");
        }
    }
    return siteUrl;
}

From source file:org.alfresco.test.wqs.web.blog.BlogComponent.java

@Override
@BeforeClass(alwaysRun = true)//ww w  .java2 s.  c  om
public void setup() throws Exception {
    super.setup();
    //        String testName = this.getClass().getSimpleName();
    siteName = this.getClass().getSimpleName() + "1";
    String hostName = (shareUrl).replaceAll(".*\\//|\\:.*", "");
    try {
        ipAddress = InetAddress.getByName(hostName).toString().replaceAll(".*/", "");
        logger.info("Ip address from Alfresco server was obtained");
    } catch (UnknownHostException | SecurityException e) {
        logger.error("Ip address from Alfresco server could not be obtained");
    }

    ;
    wqsURL = siteName + ":8080/wcmqs";
    logger.info(" wcmqs url : " + wqsURL);
    logger.info("Start Tests from: " + testName);

}

From source file:net.darkmist.clf.LogParserTest.java

public void testExtraSpacesBeforeSize() throws Exception {
    String in = "1.2.3.4 Ident User [" + LOG_TIME_AS_STR + "] \"GET http://localhost:80/ HTTP/1.1\" 200   2";
    LogEntry entry = parser.parse(in);/*w  w w . j a  v  a2s.c o  m*/

    assertEquals(InetAddress.getByName("1.2.3.4"), entry.getIP());
    assertEquals("Ident", entry.getIdent());
    assertEquals("User", entry.getUser());
    assertEquals(LOG_TIME_AS_DATE, entry.getDate());
    assertEquals("GET", entry.getMethod());
    assertEquals("http://localhost:80/", entry.getURI());
    assertEquals("HTTP/1.1", entry.getProtocol());
    assertEquals(200, entry.getStatus());
    assertEquals(2, entry.getSize());
}

From source file:org.jboss.as.test.integration.security.loginmodules.usersroles.UsersRolesLoginModuleTestCase1.java

@Deployment
public static WebArchive deployment() {
    // FIXME hack to get things prepared before the deployment happens
    try {/*w  w w. j a  v a2 s  .  com*/
        final ModelControllerClient client = ModelControllerClient.Factory
                .create(InetAddress.getByName("localhost"), 9999, getCallbackHandler());
        // create required security domains
        createSecurityDomains(client);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    WebArchive war = create("users-roles-login-module.war", UnsecuredServlet.class, null);
    WebSecurityPasswordBasedBase.printWar(war);

    return war;
}

From source file:com.digitalpebble.storm.crawler.bolt.URLPartitionerBolt.java

@Override
public void execute(Tuple tuple) {
    String url = tuple.getStringByField("url");
    Metadata metadata = null;// w  ww . j  a  v  a 2s . c  o m

    if (tuple.contains("metadata"))
        metadata = (Metadata) tuple.getValueByField("metadata");

    // maybe there is a field metadata but it can be null
    // or there was no field at all
    if (metadata == null)
        metadata = Metadata.empty;

    String partitionKey = null;
    String host = "";

    // IP in metadata?
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP)) {
        String ip_provided = metadata.getFirstValue("ip");
        if (StringUtils.isNotBlank(ip_provided)) {
            partitionKey = ip_provided;
            eventCounter.scope("provided").incrBy(1);
        }
    }

    if (partitionKey == null) {
        URL u;
        try {
            u = new URL(url);
            host = u.getHost();
        } catch (MalformedURLException e1) {
            eventCounter.scope("Invalid URL").incrBy(1);
            LOG.warn("Invalid URL: {}", url);
            // ack it so that it doesn't get replayed
            _collector.ack(tuple);
            return;
        }
    }

    // partition by hostname
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_HOST))
        partitionKey = host;

    // partition by domain : needs fixing
    else if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_DOMAIN)) {
        partitionKey = PaidLevelDomain.getPLD(host);
    }

    // partition by IP
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP) && partitionKey == null) {
        // try to get it from cache first
        partitionKey = cache.get(host);
        if (partitionKey != null) {
            eventCounter.scope("from cache").incrBy(1);
        } else {
            try {
                long start = System.currentTimeMillis();
                final InetAddress addr = InetAddress.getByName(host);
                partitionKey = addr.getHostAddress();
                long end = System.currentTimeMillis();
                LOG.debug("Resolved IP {} in {} msec for : {}", partitionKey, (end - start), url);

                // add to cache
                cache.put(host, partitionKey);

            } catch (final Exception e) {
                eventCounter.scope("Unable to resolve IP").incrBy(1);
                LOG.warn("Unable to resolve IP for: {}", host);
                _collector.ack(tuple);
                return;
            }
        }
    }

    LOG.debug("Partition Key for: {} > {}", url, partitionKey);

    _collector.emit(tuple, new Values(url, partitionKey, metadata));
    _collector.ack(tuple);
}

From source file:com.digitalpebble.stormcrawler.bolt.URLPartitionerBolt.java

@Override
public void execute(Tuple tuple) {
    String url = tuple.getStringByField("url");
    Metadata metadata = null;//  w w w .  java 2  s  . co  m

    if (tuple.contains("metadata"))
        metadata = (Metadata) tuple.getValueByField("metadata");

    // maybe there is a field metadata but it can be null
    // or there was no field at all
    if (metadata == null)
        metadata = Metadata.empty;

    String partitionKey = null;
    String host = "";

    // IP in metadata?
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP)) {
        String ip_provided = metadata.getFirstValue("ip");
        if (StringUtils.isNotBlank(ip_provided)) {
            partitionKey = ip_provided;
            eventCounter.scope("provided").incrBy(1);
        }
    }

    if (partitionKey == null) {
        URL u;
        try {
            u = new URL(url);
            host = u.getHost();
        } catch (MalformedURLException e1) {
            eventCounter.scope("Invalid URL").incrBy(1);
            LOG.warn("Invalid URL: {}", url);
            // ack it so that it doesn't get replayed
            _collector.ack(tuple);
            return;
        }
    }

    // partition by hostname
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_HOST))
        partitionKey = host;

    // partition by domain : needs fixing
    else if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_DOMAIN)) {
        partitionKey = PaidLevelDomain.getPLD(host);
    }

    // partition by IP
    if (mode.equalsIgnoreCase(Constants.PARTITION_MODE_IP) && partitionKey == null) {
        // try to get it from cache first
        partitionKey = cache.get(host);
        if (partitionKey != null) {
            eventCounter.scope("from cache").incrBy(1);
        } else {
            try {
                long start = System.currentTimeMillis();
                final InetAddress addr = InetAddress.getByName(host);
                partitionKey = addr.getHostAddress();
                long end = System.currentTimeMillis();
                LOG.debug("Resolved IP {} in {} msec for : {}", partitionKey, end - start, url);

                // add to cache
                cache.put(host, partitionKey);

            } catch (final Exception e) {
                eventCounter.scope("Unable to resolve IP").incrBy(1);
                LOG.warn("Unable to resolve IP for: {}", host);
                _collector.ack(tuple);
                return;
            }
        }
    }

    LOG.debug("Partition Key for: {} > {}", url, partitionKey);

    _collector.emit(tuple, new Values(url, partitionKey, metadata));
    _collector.ack(tuple);
}

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 a  va  2 s . c  o  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;
        }
    });
}

From source file:net.hgw4.hal.BarionetComm.java

/**
 *  create a barionet manager on port and ip specified
 * @param port/* w  w w.ja  va 2  s .  c om*/
 * @param ip_to_send_data 
 */
public BarionetComm(String port, String ip_to_send_data) {
    PropertyConfigurator.configure(
            System.getProperty("user.dir") + System.getProperty("file.separator") + "configs/log4j.properties");
    BarionetCommLogger = Logger.getLogger(BarionetComm.class);
    BarionetCommLogger.info("--> Barionet <--");
    //TODO: ottimizzare, se barionet non risponde non deve creare altri threads in wait 
    cmdResponseThread = new RunningCmdResponseThreadRun();
    thread_CmdRspBarionet = new Thread(cmdResponseThread, "Barionet - RunningCmdResponseThreadRun");
    runningCmdResponseThread = true;

    curUdpcomm = new UDPComm(port);
    thread_CmdRspBarionet.start();

    try {
        ipAdress = InetAddress.getByName(ip_to_send_data);
    } catch (UnknownHostException ex) {
        BarionetCommLogger.error(ex);
    }
}

From source file:org.tamacat.httpd.filter.geoip.GeoIPAccessControlFilter.java

boolean isIPv6(String ipaddress) {
    try {/*from   w  ww . j a v a 2  s .c  o m*/
        InetAddress address = InetAddress.getByName(ipaddress);
        return address instanceof Inet6Address;
    } catch (UnknownHostException e) {
        return false;
    }
}