Example usage for java.net InetAddress isReachable

List of usage examples for java.net InetAddress isReachable

Introduction

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

Prototype

public boolean isReachable(int timeout) throws IOException 

Source Link

Document

Test whether that address is reachable.

Usage

From source file:org.rhq.plugins.netservices.PingNetServiceComponent.java

public AvailabilityType getAvailability() {
    try {//  w w  w .  ja v a  2  s  .c o m
        String addressString = resourceContext.getPluginConfiguration().getSimple(CONFIG_ADDRESS)
                .getStringValue();
        InetAddress address = InetAddress.getByName(addressString);
        return address.isReachable(5000) ? AvailabilityType.UP : AvailabilityType.DOWN;
    } catch (Exception e) {
        return AvailabilityType.DOWN;
    }
}

From source file:org.punksearch.logic.online.Probe.java

public boolean ping(String ip) {
    boolean result;
    try {//from   www .j  a  v a 2  s  . c  om
        InetAddress ia = InetAddress.getByName(ip);
        result = ia.isReachable(PROBE_TIMEOUT);
    } catch (Exception e) {
        log.warn("Exception during ping: " + e.getMessage());
        result = false;
    }
    log.debug("Probe (ping): " + ip + " = " + result);
    return result;
}

From source file:de.burrotinto.jKabel.dbauswahlAS.DBAuswahlAAS.java

/**
 * Versucht sich mit der entfernten Datenbank zu verbinden
 *
 * @param ip Adresse der DB//from ww w  .j ava2 s.  c  o m
 * @return Wrapper zur angeforderten DB, Null wenn keine Verbindung mglich war.
 */
private IDBWrapper connectRemoteDB(InetAddress ip) {
    try {
        if (ip.isReachable(100))
            try {
                HSQLDBWrapper idbWrapper = new HSQLDBWrapper(ip);
                serverIP = ip;
                return idbWrapper;
            } catch (Exception e) {
                serverIP = null;
                return null;
            }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.openhab.binding.fronius.handler.FroniusBridgeHandler.java

/**
 * Start the job refreshing the data/*from w ww. ja  va2 s  . c  om*/
 */
private void startAutomaticRefresh(FroniusBridgeConfiguration config) {
    if (refreshJob == null || refreshJob.isCancelled()) {
        Runnable runnable = () -> {
            boolean online = false;
            try {
                InetAddress inet;
                inet = InetAddress.getByName(config.hostname);
                if (inet.isReachable(5000)) {
                    online = true;
                }
            } catch (IOException e) {
                logger.debug("Connection Error: {}", e.getMessage());
                return;
            }

            if (!online) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR,
                        "hostname or ip is not reachable");
            } else {
                updateStatus(ThingStatus.ONLINE);
                for (FroniusBaseThingHandler service : services) {
                    service.refresh(config);
                }
            }
        };

        int delay = (config.refreshInterval != null) ? config.refreshInterval.intValue()
                : DEFAULT_REFRESH_PERIOD;
        refreshJob = scheduler.scheduleWithFixedDelay(runnable, 0, delay, TimeUnit.SECONDS);
    }
}

From source file:com.opensoc.enrichment.adapters.whois.WhoisHBaseAdapterTest.java

protected void setUp() throws Exception {
    super.setUp();
    Properties prop = super.getTestProperties();
    assertNotNull(prop);/* w  w w .ja  v  a2 s. c  o m*/

    if (skipTests(this.getMode())) {
        return;//skip tests
    }

    String[] zk = prop.get("kafka.zk.list").toString().split(",");

    for (String z : zk) {
        InetAddress address = InetAddress.getByName(z);
        boolean reachable = address.isReachable(100);

        if (!reachable) {
            this.setMode("local");
            break;
            //throw new Exception("Unable to reach zookeeper, skipping WHois adapter test");
        }

        System.out.println("kafka.zk.list =" + (String) prop.get("kafka.zk.list"));
        System.out.println("kafka.zk.list =" + (String) prop.get("kafka.zk.port"));
        System.out.println("kafka.zk.list =" + (String) prop.get("bolt.enrichment.cif.tablename"));

    }

    if (skipTests(this.getMode())) {
        System.out.println("Local Mode Skipping tests !! ");
    } else {
        whoisHbaseAdapter = new WhoisHBaseAdapter((String) prop.get("bolt.enrichment.whois.hbase.table.name"),
                (String) prop.get("kafka.zk.list"), (String) prop.get("kafka.zk.port"));
        connected = whoisHbaseAdapter.initializeAdapter();
        assertTrue(connected);
    }

}

From source file:org.ojbc.util.camel.processor.audit.SQLLoggingProcessorTest.java

private void assertDbContents()
        throws UnknownHostException, IOException, SAXException, ParserConfigurationException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);//from  w  w  w  .  ja v  a2s  .com

    List<Map<String, Object>> rows = sqlLoggingProcessor.getJdbcTemplate()
            .queryForList("select * from AuditLog");

    assertEquals(1, rows.size());

    Map<String, Object> row = rows.get(0);

    assertEquals(row.get("origin"), "http://www.ojbc.org/from");
    assertEquals(row.get("destination"), "http://www.ojbc.org/to");
    assertEquals(row.get("messageID"), "12345");
    assertEquals(row.get("federationID"), "HIJIS:IDP:HCJDC:USER:admin");
    assertEquals(row.get("employerName"), "Department of Attorney General");
    assertEquals(row.get("employerSubUnitName"), "HCJDC ISDI");
    assertEquals(row.get("userLastName"), "owen");
    assertEquals(row.get("userFirstName"), "andrew");
    assertEquals(row.get("identityProviderID"), "https://idp.ojbc-local.org:9443/idp/shibboleth");
    assertEquals(row.get("camelContextID"),
            "org.ojbc.util.camel.processor.audit.SQLLoggingProcessorTest CamelContext");

    String hostAddress = (String) row.get("hostAddress");
    InetAddress ia = InetAddress.getByName(hostAddress);
    assertTrue(ia.isReachable(1000));

    String messageDocS = (String) row.get("soapMessage");

    Document messageDoc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(messageDocS)));

    Element ee = messageDoc.getDocumentElement();
    assertEquals("root", ee.getLocalName());
    assertEquals("http://ojbc.org", ee.getNamespaceURI());
    NodeList nl = ee.getElementsByTagNameNS("http://ojbc.org", "child");
    ee = (Element) nl.item(0);
    assertEquals("Child contents", ee.getTextContent());

    Date d = (Date) row.get("timestamp");
    DateTime dt = new DateTime(d);
    assertEquals(0, Minutes.minutesBetween(new DateTime(), dt).getMinutes());
}

From source file:org.manalith.ircbot.plugin.ping.PingPlugin.java

@BotCommand("")
public String ping(@Option(name = "?", help = "?  ?? ? IP ") String uri) {
    InetAddress addr;

    try {//from w w  w .  ja va  2s  .co m
        addr = InetAddress.getByName(uri);
    } catch (UnknownHostException e) {
        return "[Ping]   .";
    }

    try {
        return String.format("[Ping] %s(%s) is %s: ", addr.getHostName(), addr.getHostAddress(),
                addr.isReachable(3000) ? "reachable" : "not reachable");
    } catch (IOException e) {
        return String.format("[Ping] ?  ?.(%s)", e.getMessage());
    }
}

From source file:de.vanita5.twittnuker.util.net.TwidereHostAddressResolver.java

@Override
public String resolve(final String host) throws IOException {
    if (host == null)
        return null;
    if (isValidIpAddress(host))
        return null;
    // First, I'll try to load address cached.
    if (mHostCache.containsKey(host)) {
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got cached address " + mHostCache.get(host) + " for host " + host);
        }//from   w  ww . ja v  a2  s .  c  o  m
        return mHostCache.get(host);
    }
    // Then I'll try to load from custom host mapping.
    // Stupid way to find top domain, but really fast.
    if (mHostMapping.contains(host)) {
        final String mappedAddr = mHostMapping.getString(host, null);
        mHostCache.put(host, mappedAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got mapped address " + mappedAddr + " for host " + host);
        }
        return mappedAddr;
    }
    mSystemHosts.reloadIfNeeded();
    if (mSystemHosts.contains(host)) {
        final String hostAddr = mSystemHosts.getAddress(host);
        mHostCache.put(host, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got mapped address " + hostAddr + " for host " + host);
        }
        return hostAddr;
    }
    final String customMappedHost = findHost(host);
    if (customMappedHost != null) {
        mHostCache.put(host, customMappedHost);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Got mapped address " + customMappedHost + " for host " + host);
        }
        return customMappedHost;
    }
    initDns();
    // Use TCP DNS Query if enabled.
    if (mDns != null && mPreferences.getBoolean(KEY_TCP_DNS_QUERY, false)) {
        final Name name = new Name(host);
        final Record query = Record.newRecord(name, Type.A, DClass.IN);
        if (query == null)
            return host;
        final Message response;
        try {
            response = mDns.send(Message.newQuery(query));
        } catch (final IOException e) {
            return host;
        }
        if (response == null)
            return host;
        final Record[] records = response.getSectionArray(Section.ANSWER);
        if (records == null || records.length < 1)
            throw new IOException("Could not find " + host);
        String hostAddr = null;
        // Test each IP address resolved.
        for (final Record record : records) {
            if (record instanceof ARecord) {
                final InetAddress ipv4Addr = ((ARecord) record).getAddress();
                if (ipv4Addr.isReachable(300)) {
                    hostAddr = ipv4Addr.getHostAddress();
                }
            } else if (record instanceof AAAARecord) {
                final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
                if (ipv6Addr.isReachable(300)) {
                    hostAddr = ipv6Addr.getHostAddress();
                }
            }
            if (hostAddr != null) {
                mHostCache.put(host, hostAddr);
                if (Utils.isDebugBuild()) {
                    Log.d(RESOLVER_LOGTAG, "Resolved address " + hostAddr + " for host " + host);
                }
                return hostAddr;
            }
        }
        // No address is reachable, but I believe the IP is correct.
        final Record record = records[0];
        if (record instanceof ARecord) {
            final InetAddress ipv4Addr = ((ARecord) record).getAddress();
            hostAddr = ipv4Addr.getHostAddress();
        } else if (record instanceof AAAARecord) {
            final InetAddress ipv6Addr = ((AAAARecord) record).getAddress();
            hostAddr = ipv6Addr.getHostAddress();
        } else if (record instanceof CNAMERecord)
            return resolve(((CNAMERecord) record).getTarget().toString());
        mHostCache.put(host, hostAddr);
        if (Utils.isDebugBuild()) {
            Log.d(RESOLVER_LOGTAG, "Resolved address " + hostAddr + " for host " + host);
        }
        return hostAddr;
    }
    if (Utils.isDebugBuild()) {
        Log.w(RESOLVER_LOGTAG, "Resolve address " + host + " failed, using original host");
    }
    return host;
}

From source file:com.perceptive.epm.perkolcentral.action.ImageNowLicenseAction.java

public String executeINowLicenseRequestView() throws ExceptionWrapper {
    String result = ERROR;//from  w  ww .j  a v  a  2  s  .co m
    try {

        String hostAddress = this.imagenowlicenses.getHostname();
        System.out.println("Hostname is: " + hostAddress);

        InetAddress address = InetAddress.getByName(hostAddress);
        boolean reachable = address.isReachable(5000);
        System.out.println("Is Host Reachable: " + reachable);

        if (!reachable) {
            System.out.println("Not Reachable");
            errorMessage = errorMessage + "* Hostname not Reachable." + IOUtils.LINE_SEPARATOR;
            return result;
        } else {
            result = SUCCESS;
            System.out.println("RESULT is: " + result);
            rallyGroups = groupsBL.getAllRallyGroups();
            getSpecificGroupsThatRequireINLicense();
            if (StringUtils.isNotEmpty(dupsub)) {
                errorMessage = errorMessage
                        + "* You are trying to re-submit a form that you have already submitted.Please wait for some time."
                        + IOUtils.LINE_SEPARATOR;
            }

        }
    } catch (Exception ex) {
        //throw new ExceptionWrapper(ex);
        errorMessage = errorMessage + "* Invalid Hostname." + IOUtils.LINE_SEPARATOR;
        result = ERROR;
    }

    return result;
}

From source file:com.mgmtp.perfload.core.client.config.LtProcessModule.java

/**
 * <p>/*from  www.  ja  v a  2 s  .  c om*/
 * Provides a list of configured local ip addresses. If the client has multiple network
 * interface cards, multiple ip addresses may be configured. The format is
 * {@code ipaddress.<index>}, e. g.:
 * </p>
 * <p>
 * {@code ipaddress.1=192.168.19.121}<br />
 * {@code ipaddress.2=192.168.19.122}<br />
 * {@code ipaddress.3=192.168.19.123}<br />
 * {@code ipaddress.4=192.168.19.124}<br />
 * {@code ipaddress.5=192.168.19.125}
 * </p>
 * 
 * @param properties
 *            the properties
 * @return a list of {@link InetAddress} objects
 */
@Provides
@Singleton
protected List<InetAddress> provideLocalAddresses(final PropertiesMap properties) throws IOException {
    Collection<String> addresses = Maps.filterKeys(properties, new Predicate<String>() {
        @Override
        public boolean apply(final String input) {
            return input.startsWith("ipaddress.");
        }
    }).values();

    List<InetAddress> result = newArrayList();

    for (String addressString : addresses) {
        InetAddress address = InetAddress.getByName(addressString);
        if (!address.isReachable(2000)) { // 2 sec
            throw new IllegalStateException("Configured IP address not reachable: " + address);
        }
        result.add(address);
    }

    return ImmutableList.copyOf(result);
}