Example usage for java.net InetAddress getHostName

List of usage examples for java.net InetAddress getHostName

Introduction

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

Prototype

public String getHostName() 

Source Link

Document

Gets the host name for this IP address.

Usage

From source file:org.peterbaldwin.vlcremote.sweep.Worker.java

@Override
public void run() {
    // Note: InetAddress#isReachable(int) always returns false for Windows
    // hosts because applications do not have permission to perform ICMP
    // echo requests.
    for (;;) {/*from w ww  . j  a  v  a  2s.  c  o m*/
        byte[] ipAddress = mManager.pollIpAddress();
        if (ipAddress == null) {
            break;
        }
        try {
            InetAddress address = InetAddress.getByAddress(ipAddress);
            String hostAddress = address.getHostAddress();
            URL url = createUrl("http", hostAddress, mPort, mPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            try {
                int responseCode = connection.getResponseCode();
                String responseMessage = connection.getResponseMessage();
                InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK)
                        ? connection.getInputStream()
                        : connection.getErrorStream();
                if (inputStream != null) {
                    try {
                        int length = connection.getContentLength();
                        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
                        entity.setContentType(connection.getContentType());

                        // Copy the entire response body into memory
                        // before the HTTP connection is closed:
                        String body = EntityUtils.toString(entity);

                        ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1);
                        String hostname = address.getHostName();
                        StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage);
                        HttpResponse response = new BasicHttpResponse(statusLine);
                        response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort);
                        response.setEntity(new StringEntity(body));
                        mCallback.onReachable(ipAddress, response);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    Log.w(TAG, "InputStream is null");
                }
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            mCallback.onUnreachable(ipAddress, e);
        }
    }
}

From source file:com.akretion.kettle.steps.terminatooor.ScriptValuesAddedFunctions.java

public static String resolveIP(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    String sRC = "";
    if (ArgList.length == 2) {
        try {/*from ww w  .j  ava  2 s.co  m*/
            InetAddress addr = InetAddress.getByName((String) ArgList[0]);
            if (((String) ArgList[1]).equals("IP"))
                sRC = addr.getHostName();
            else
                sRC = addr.getHostAddress();
            if (sRC.equals((String) ArgList[0]))
                sRC = "-";
        } catch (Exception e) {
            sRC = "-";
        }
    } else {
        throw new RuntimeException("The function call resolveIP requires 2 arguments.");
    }

    return sRC;
}

From source file:com.panet.imeta.trans.steps.scriptvalues_mod.ScriptValuesAddedFunctions.java

public static String resolveIP(Context actualContext, Scriptable actualObject, Object[] ArgList,
        Function FunctionContext) {
    String sRC = "";
    if (ArgList.length == 2) {
        try {/*from  w w w . ja v  a 2 s.  c  o m*/
            InetAddress addr = InetAddress.getByName(Context.toString(ArgList[0]));
            if (Context.toString(ArgList[1]).equals("IP"))
                sRC = addr.getHostName();
            else
                sRC = addr.getHostAddress();
            if (sRC.equals(Context.toString(ArgList[0])))
                sRC = "-";
        } catch (Exception e) {
            sRC = "-";
        }
    } else {
        throw Context.reportRuntimeError("The function call resolveIP requires 2 arguments.");
    }

    return sRC;
}

From source file:org.opennms.ng.services.collectd.Collectd.java

/**
 * This method is responsible for handling interfaceDeleted events.
 *
 * @param event The event to process./*from   ww  w. j a v  a2  s .co m*/
 * @throws InsufficientInformationException
 */
private void handleInterfaceDeleted(Event event) throws InsufficientInformationException {
    EventUtils.checkNodeId(event);

    String ipAddr = event.getInterface();
    if (EventUtils.isNonIpInterface(ipAddr)) {
        LOG.debug("handleInterfaceDeleted: the deleted interface was a non-ip interface. Nothing to do here.");
        return;
    }

    Long nodeId = event.getNodeid();

    // Iterate over the collectable services list and mark any entries
    // which match the deleted nodeId/IP address pair for deletion
    synchronized (getCollectableServices()) {
        CollectableService cSvc = null;
        ListIterator<CollectableService> liter = getCollectableServices().listIterator();
        while (liter.hasNext()) {
            cSvc = liter.next();

            // Only interested in entries with matching nodeId and IP
            // address
            InetAddress addr = (InetAddress) cSvc.getAddress();
            if (!(cSvc.getNodeId() == nodeId && addr.getHostName().equals(ipAddr))) {
                continue;
            }

            synchronized (cSvc) {
                // Retrieve the CollectorUpdates object associated with
                // this CollectableService if one exists.
                CollectorUpdates updates = cSvc.getCollectorUpdates();

                // Now set the update's deletion flag so the next
                // time it is selected for execution by the scheduler
                // the collection will be skipped and the service will not
                // be rescheduled.
                LOG.debug(
                        "Marking CollectableService for deletion because an interface was deleted:  Service nodeid={}, "
                                + "deleted node:{}service address:{}deleted interface:{}",
                        cSvc.getNodeId(), nodeId, addr.getHostName(), ipAddr);

                updates.markForDeletion();
            }

            // Now safe to remove the collectable service from
            // the collectable services list
            liter.remove();
        }
    }

    LOG.debug("interfaceDeletedHandler: processing of interfaceDeleted event for {}/{} completed", nodeId,
            ipAddr);
}

From source file:org.lnicholls.galleon.server.Server.java

private void printServerProperties() {
    try {//ww w .ja va  2 s  . c om
        InetAddress inetAddress = InetAddress.getLocalHost();

        log.info("Galleon Version=" + getVersion());
        log.info("Local IP=" + Tools.getLocalIpAddress());
        log.info("Host=" + inetAddress.getHostName());

        Tools.logMemory();
    } catch (UnknownHostException ex) {
        Tools.logException(Server.class, ex);
    } catch (Throwable ex) {
        ex.printStackTrace();
    }
}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.AutConfigComponent.java

/**
 * @return if the current aut starter is localhost
 *///from  w  ww .  j av a2s. c  o m
private boolean isLocalhost() {
    boolean enable;
    try {
        final String serverComboText = getServerCombo().getText();
        final InetAddress localHost = InetAddress.getLocalHost();
        final String canonicalHostName = localHost.getCanonicalHostName();
        enable = (Constants.LOCALHOST1.equals(serverComboText.toLowerCase())
                || Constants.LOCALHOST2.equals(serverComboText)
                || localHost.getHostName().equals(serverComboText)
                || localHost.getHostAddress().equals(serverComboText)
                || (canonicalHostName != null && canonicalHostName.equals(serverComboText)));
    } catch (UnknownHostException e) {
        enable = false;
    }
    return enable;
}

From source file:name.livitski.databag.cli.Launcher.java

public void run() {
    try {//from w w w.j  ava2s.co  m
        setStatus(Status.OK);
        if (!hasOption(NOBANNER_OPTION))
            banner();
        Level requestedLogLevel = getRequestedLogLevel();
        setLogLevel(requestedLogLevel);
        log().finer("Verbosity level " + requestedLogLevel);
        if (hasOption(HELP_COMMAND)) {
            SYNTAX.usage(getOutputStream());
            return;
        }
        try {
            boolean doneSomething = false;
            if (hasOption(CREATE_OPTION)) {
                create();
                doneSomething = true;
            } else
                open();
            // no database - print usage
            if (null == db) {
                log().warning("Could not find a bag on \"" + getMedium() + "\", giving up.");
                showHelpHint();
                return;
            }
            if (hasOption(SCHEMA_EVOLUTION_OPTION))
                db.setSchemaEvolutionAllowed(true);
            // determine current user and host
            String user = System.getProperty(USER_NAME_PROPERTY, "default_user");
            InetAddress localAddress = InetAddress.getLocalHost();
            String host = localAddress.getCanonicalHostName();
            if ("127.0.0.1".equals(host) || "localhost".equalsIgnoreCase(host))
                host = localAddress.getHostName();
            // locate the copy of shared storage to work with
            Replicas replicaQueries = new Replicas(db, getConfiguration());
            ReplicaInfo replica;
            File local = getLocal();
            replica = replicaQueries.findReplica(user, host, null == local ? null : local.getPath());
            if (null == replica) {
                // new local copy being created
                if (null != local) {
                    if (hasOption(DROP_COMMAND))
                        log().warning("Replica at '" + local + "' shall not be created when running a --"
                                + DROP_COMMAND + " command");
                    else {
                        ReplicaManager rmgr = new ReplicaManager(db, getConfiguration());
                        Number rid = rmgr.registerNewReplica(user, host, local.getPath());
                        replica = replicaQueries.findReplica(rid);
                        doneSomething = true;
                    }
                }
                // no local copy - print warning
                else
                    log().warning(
                            "Local replica of bag " + getMedium() + " not found for " + user + '@' + host);
            }
            // drop request
            if (hasOption(DROP_COMMAND)) {
                if (hasOption(SAVE_OPTION))
                    throw new IllegalArgumentException("--" + DROP_COMMAND
                            + " command does not support output redirection (--" + SAVE_OPTION + " option)");
                DropType type = getDropType();
                switch (type) {
                case REPLICA:
                    if (null == replica)
                        throw new IllegalStateException("Local replica for " + user + '@' + host
                                + " does not exist" + (null == local ? "" : " at " + local));
                    else if (null == local)
                        throw new IllegalArgumentException(
                                "--" + DROP_COMMAND + " requires an explicit replica location to drop.");
                    else
                        dropReplica(replica);
                    break;
                case FILTER:
                    if (hasOption(SET_OPTION) || hasOption(LOAD_OPTION))
                        throw new IllegalArgumentException("Options --" + SET_OPTION + " and --" + LOAD_OPTION
                                + " conflict with --" + DROP_COMMAND + ' ' + DropType.REPLICA
                                + " command. Please remove these options before proceeding.");
                    String[] optionValues = options.getOptionValues(DROP_COMMAND);
                    dropFilter(1 < optionValues.length && FORCE_OPTION.equalsIgnoreCase(optionValues[1]));
                    break;
                default:
                    throw new UnsupportedOperationException("Unknown type of a record to drop: " + type);
                }
                return;
            }
            // update filters if necessary before proceeding
            if (hasFilterOption()) {
                File fileToLoad = getFileToLoad();
                if (null != fileToLoad) {
                    if (hasOption(SET_OPTION))
                        throw new IllegalArgumentException("Option --" + SET_OPTION + " conflicts with --"
                                + LOAD_OPTION + ". Please remove either of these options before proceeding.");
                    loadFilter(fileToLoad);
                    doneSomething = true;
                } else {
                    String[] patternsToSet = getPatternsToSet();
                    if (null != patternsToSet) {
                        setFilter(patternsToSet);
                        doneSomething = true;
                    }
                }
            }
            // TODO: modify these checks when overloading --set or --load operations for
            // non-filter entities
            else if (hasOption(SET_OPTION))
                throw new IllegalArgumentException("Option --" + SET_OPTION + " requires a --" + FILTER_OPTION
                        + " option with a filter name");
            else if (hasOption(LOAD_OPTION))
                throw new IllegalArgumentException("Option --" + LOAD_OPTION + " requires a --" + FILTER_OPTION
                        + " option with a filter name");
            // default replica designation
            if (isLocalBecomingDefault()) {
                ReplicaManager rmgr = new ReplicaManager(db, getConfiguration());
                Number rid = replica.getId();
                rmgr.setDefaultReplica(rid);
                doneSomething = true;
            }
            // default filter designation
            if (isFilterBecomingDefault()) {
                // error if replica is null
                if (null == replica)
                    throw new IllegalArgumentException("--" + LOCAL_OPTION
                            + " option is required when setting the default filter for a replica.");
                setDefaultFilter(replica);
                doneSomething = true;
            }
            // list request
            if (hasOption(LIST_COMMAND)) {
                ListType type = getListType();
                switch (type) {
                case FILES:
                    listFiles();
                    break;
                case REPLICAS:
                    if (hasFilterOption())
                        log().warning("Option --" + FILTER_OPTION
                                + " does not apply when listing replicas and will be ignored.");
                    listReplicas(user, host);
                    break;
                case FILTER:
                    listFilter();
                    break;
                case FILTERS:
                    if (hasFilterOption())
                        log().warning("Option --" + FILTER_OPTION
                                + " does not apply when listing filters and will be ignored.");
                    listFilters(replica);
                    break;
                default:
                    throw new UnsupportedOperationException("Unknown type of record(s) to list: " + type);
                }
                return;
            }
            // history request
            if (hasOption(HISTORY_COMMAND)) {
                listVersions();
                return;
            }
            // purge request
            if (hasOption(LOG_COMMAND)) {
                showLog();
                return;
            }
            // purge request
            if (hasOption(PURGE_COMMAND)) {
                if (hasOption(SAVE_OPTION))
                    throw new IllegalArgumentException("--" + PURGE_COMMAND
                            + " command does not support output redirection (--" + SAVE_OPTION + " option)");
                purge();
                return;
            }
            // file restore request
            if (hasOption(RESTORE_COMMAND)) {
                RestoreCommand cmd = new RestoreCommand(db, replica, getConfiguration());
                cmd.setNameOption(optionValue(RESTORE_COMMAND));
                cmd.setFileId(getFileId());
                cmd.setVersionId(getVersionId());
                cmd.setAsOfTime(getAsOfTimestamp());
                cmd.setOutputFile(getOutputFile(true));
                cmd.run();
                return;
            }
            // file undo request
            if (hasOption(UNDO_COMMAND)) {
                UndoCommand cmd = new UndoCommand(db, replica, getConfiguration());
                cmd.setNameOption(optionValue(UNDO_COMMAND));
                cmd.setFileId(getFileId());
                cmd.setVersionId(getVersionId());
                cmd.setAsOfTime(getAsOfTimestamp());
                cmd.setNoSync(hasOption(NOSYNC_OPTION));
                cmd.run();
                return;
            }
            // sync by default, unless asked not to
            if (hasOption(NOSYNC_OPTION)) {
                if (hasOption(SYNC_COMMAND))
                    throw new IllegalArgumentException(
                            "Command --" + SYNC_COMMAND + " does not allow option --" + NOSYNC_OPTION);
                // display a warning when sync is disabled and nothing else is done    
                else if (!doneSomething) {
                    log().warning(
                            "Nothing to do - you disabled synchronization, but didn't change any settings.");
                }
            } else if (null != replica) {
                if (hasOption(SAVE_OPTION))
                    log().warning("Synchronization does not support output redirection (--" + SAVE_OPTION
                            + " option). That option will be ignored.");
                SyncCommand cmd = new SyncCommand(db, replica, getConfiguration());
                cmd.setPattern(optionValue(SYNC_COMMAND));
                cmd.setFileId(getFileId());
                cmd.run();
                return;
            }
        } catch (IncompatibleSchemaException outdated) {
            if (outdated.isUpgradable()) {
                log().severe(outdated.getMessage());
                log().severe("Back up your database and use the --" + SCHEMA_EVOLUTION_OPTION
                        + " option to allow schema upgrades.");
            } else
                log().log(Level.SEVERE, outdated.getMessage(), outdated);
            setStatus(Status.OBSOLETE);
        } catch (Exception ex) {
            log().log(Level.SEVERE, ex.getMessage(), ex);
            setStatus(Status.RUNTIME);
        } finally {
            if (null != db)
                try {
                    db.close();
                } catch (DBException ex) {
                    log().log(Level.WARNING, ex.getMessage(), ex);
                }
        }
    } finally {
        if (null != this.out) {
            this.out.close();
            this.out = null;
        }
    }
}

From source file:org.pentaho.di.trans.steps.script.ScriptAddedFunctions.java

public static String resolveIP(ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
        Object FunctionContext) {
    String sRC = "";
    if (ArgList.length == 2) {
        try {//from  w ww . j  av  a2  s  .c  om
            InetAddress addr = InetAddress.getByName((String) ArgList[0]);
            if (((String) ArgList[1]).equals("IP")) {
                sRC = addr.getHostName();
            } else {
                sRC = addr.getHostAddress();
            }
            if (sRC.equals(ArgList[0])) {
                sRC = "-";
            }
        } catch (Exception e) {
            sRC = "-";
        }
    } else {
        throw new RuntimeException("The function call resolveIP requires 2 arguments.");
    }

    return sRC;
}

From source file:org.rdv.rbnb.RBNBController.java

protected RBNBController() {
    // get the system host name and append it to the sink name
    try {/*w  w w .  j a  v  a 2 s .c o m*/
        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();
        rbnbSinkName += "@" + hostname;
    } catch (UnknownHostException e) {
    }

    state = STATE_DISCONNECTED;

    rbnbHostName = DEFAULT_RBNB_HOST_NAME;
    rbnbPortNumber = DEFAULT_RBNB_PORT_NUMBER;

    requestIsMonitor = false;

    dropData = false;

    location = System.currentTimeMillis() / 1000d;
    playbackRate = 1;
    timeScale = 1;

    requestedChannels = new ChannelMap();

    channelManager = new ChannelManager();
    metadataManager = new MetadataManager(this);
    markerManager = new MarkerManager(this);

    timeListeners = new ArrayList<TimeListener>();
    stateListeners = new ArrayList<StateListener>();
    subscriptionListeners = new ArrayList<SubscriptionListener>();
    playbackRateListeners = new ArrayList<PlaybackRateListener>();
    timeScaleChangeListeners = new ArrayList<TimeScaleListener>();
    messageListeners = new ArrayList<MessageListener>();
    connectionListeners = new ArrayList<ConnectionListener>();

    run();
}

From source file:com.amalto.workbench.utils.LocalTreeObjectRepository.java

private String UnifyUrl(String url) {
    Pattern mask = Pattern.compile("http://(.*?):(.*)");//$NON-NLS-1$
    Matcher matcher = mask.matcher(url);
    if (matcher.find()) {
        String ip = matcher.group(1);
        String ipAlias = "";//$NON-NLS-1$
        String hostName = "";//$NON-NLS-1$
        try {/*from   w ww  .  j av a 2s  . c  o m*/
            InetAddress addr = InetAddress.getLocalHost();
            ipAlias = addr.getHostAddress().toString();
            hostName = addr.getHostName().toString();
            if (ip.equals("127.0.0.1") || ip.equals(ipAlias) || ip.equals(hostName) || ip.equals("localhost")) {//$NON-NLS-1$//$NON-NLS-2$
                url = "http://" + ipAlias + ":" + matcher.group(2);//$NON-NLS-1$//$NON-NLS-2$
            }
        } catch (UnknownHostException e) {
            log.error(e.getMessage(), e);
        }
    }
    return url;
}