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:net.lightbody.bmp.proxy.jetty.http.HttpContext.java

/** Get the hosts for the context.
 *///  w  ww.  j  a va 2  s  . c om
public String[] getHosts() {
    if (_hosts == null || _hosts.size() == 0)
        return null;
    String[] hosts = new String[_hosts.size()];
    for (int i = 0; i < hosts.length; i++) {
        InetAddress a = (InetAddress) _hosts.get(i);
        if (a != null)
            hosts[i] = a.getHostName();
    }
    return hosts;
}

From source file:org.apache.hadoop.mapreduce.v2.app.job.impl.TaskAttemptImpl.java

protected String resolveHost(String src) {
    String result = src; // Fallback in case of failure.
    try {//  w w w .  j  a v  a2s .  c  o  m
        InetAddress addr = InetAddress.getByName(src);
        result = addr.getHostName();
    } catch (UnknownHostException e) {
        LOG.warn("Failed to resolve address: " + src + ". Continuing to use the same.");
    }
    return result;
}

From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java

/**
 * This method is responsible for creating and sending a
 * 'suspectScanCompleted' event to Eventd
 *
 * @param ipAddr IP address of the interface for which the suspect scan has completed
 *///from  w  w w .j a v  a 2s .  c o m
private void createAndSendSuspectScanCompletedEvent(InetAddress ipAddr) {
    EventBuilder bldr = createEventBuilder(EventConstants.SUSPECT_SCAN_COMPLETED_EVENT_UEI);
    bldr.setInterface(ipAddr);
    bldr.addParam(EventConstants.PARM_IP_HOSTNAME, ipAddr.getHostName());
    sendEvent(bldr.getEvent());
}

From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java

/**
 * This method is responsible for creating and sending a
 * 'nodeGainedInterface' event to Eventd
 *
 * @param nodeId Interface's parent node identifier.
 * @param ipAddr Interface's IP address//from ww w  .j av a2 s  . c o  m
 */
private void createAndSendNodeGainedInterfaceEvent(int nodeId, InetAddress ipAddr) {

    EventBuilder bldr = createEventBuilder(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI);
    bldr.setNodeid(nodeId);
    bldr.setInterface(ipAddr);
    bldr.addParam(EventConstants.PARM_IP_HOSTNAME, ipAddr.getHostName());
    bldr.addParam(EventConstants.PARM_METHOD, "icmp");

    sendEvent(bldr.getEvent());
}

From source file:pl.otros.logview.gui.actions.ConnectToSocketHubAppenderAction.java

@Override
public void actionPerformed(ActionEvent arg0) {

    boolean accepted = chooseLogImporter();
    if (!accepted) {
        return;// w w w.  j av a  2s .co  m
    }

    logViewPanelWrapper = new LogViewPanelWrapper("Socket", null, TableColumns.values(), getOtrosApplication());

    logViewPanelWrapper.goToLiveMode();
    BaseConfiguration configuration = new BaseConfiguration();
    configuration.addProperty(ConfKeys.TAILING_PANEL_PLAY, true);
    configuration.addProperty(ConfKeys.TAILING_PANEL_FOLLOW, true);
    logDataCollector = new BufferingLogDataCollectorProxy(logViewPanelWrapper.getDataTableModel(), 4000,
            configuration);
    //      JTabbedPane jTabbedPane = getOtrosApplication().getJTabbedPane();
    //      int tabCount = jTabbedPane.getTabCount();
    String hostPort = "Log4j SocketHub " + host + ":" + port;

    try {

        final LogImporter logImporter = new Log4jSerilizedLogImporter();
        logImporter.init(new Properties());
        final ParsingContext parsingContext = new ParsingContext(hostPort, hostPort);

        logImporter.initParsingContext(parsingContext);
        TailLogActionListener.ParsingContextStopperForClosingTab contextStopperForClosingTab = new ParsingContextStopperForClosingTab(
                parsingContext);
        TailLogActionListener.ReadingStopperForRemove readingStopperForRemove = new TailLogActionListener.ReadingStopperForRemove(
                contextStopperForClosingTab, logDataCollector);
        logViewPanelWrapper.addHierarchyListener(readingStopperForRemove);

        getOtrosApplication().addClosableTab(hostPort, hostPort, Icons.PLUGIN_CONNECT, logViewPanelWrapper,
                true);

        Runnable r = new Runnable() {

            @Override
            public void run() {
                InetAddress inetAddress = socket.getInetAddress();
                int port2 = socket.getPort();
                InputStream inputStream = null;
                Socket s = socket;
                while (parsingContext.isParsingInProgress()) {
                    try {
                        inputStream = s.getInputStream();
                        BufferedInputStream bin = new BufferedInputStream(inputStream);
                        LOGGER.info(String.format("Connect to SocketHubAppender to %s:%d",
                                inetAddress.getHostAddress(), port2));
                        logImporter.importLogs(bin, logDataCollector, parsingContext);
                        getOtrosApplication().getStatusObserver().updateStatus(
                                "Loading logs from Log4j SocketHubAppender finished",
                                StatusObserver.LEVEL_WARNING);
                    } catch (IOException e1) {
                        LOGGER.warning(String.format("Problem with connecting to %s:%d: %s",
                                inetAddress.getHostAddress(), port2, e1.getMessage()));
                    }
                    try {
                        LOGGER.fine("Reconnecting in " + RECONNECT_TIME + "ms");
                        Thread.sleep(RECONNECT_TIME);
                    } catch (InterruptedException e) {
                        LOGGER.warning("Waiting thread interrupted" + e.getMessage());
                    }
                    if (parsingContext.isParsingInProgress()) {
                        try {
                            LOGGER.fine(String.format("Connecting to Log4j SocketHubAppender at %s:%d",
                                    inetAddress.getHostName(), port2));
                            s = new Socket(inetAddress, port2);
                        } catch (IOException e) {
                            LOGGER.warning(String.format("Problem with connecting to %s:%d: %s",
                                    inetAddress.getHostAddress(), port2, e.getMessage()));
                        }
                    }
                }
                LOGGER.info(
                        String.format("Importing from %s:%d is finished", inetAddress.getHostName(), port2));
            }
        };
        new Thread(r, hostPort).start();

    } catch (Exception e) {
        JOptionPane.showMessageDialog((Component) arg0.getSource(), "Error importing logs from " + hostPort,
                "Error importing logs", JOptionPane.ERROR_MESSAGE);

    }

}

From source file:com.cnaude.purpleirc.PurpleIRC.java

public String getPlayerHost(final String playerIP) {
    if (playerIP == null) {
        return "unknown";
    }/*from  w  w w  . java  2 s. c  o  m*/
    if (hostCache.containsKey(playerIP)) {
        return hostCache.get(playerIP);
    } else {
        getServer().getScheduler().runTaskLaterAsynchronously(this, new Runnable() {
            @Override
            public void run() {
                long a = System.currentTimeMillis();
                InetAddress addr = null;
                try {
                    addr = InetAddress.getByName(playerIP);
                } catch (UnknownHostException ex) {
                    logError(ex.getMessage());
                }
                String host;
                if (addr != null) {
                    host = addr.getHostName();
                } else {
                    host = playerIP;
                }
                hostCache.put(playerIP, host);
                logDebug(
                        "getPlayerHost[" + (System.currentTimeMillis() - a) + "ms] " + playerIP + " = " + host);
            }
        }, 0);
        return playerIP;
    }
}

From source file:org.pentaho.di.core.Const.java

/**
 * Determine the hostname of the machine Kettle is running on
 *
 * @return The hostname/*from w  w  w  . ja  va 2 s.  com*/
 */
public static final String getHostname() {

    if (cachedHostname != null) {
        return cachedHostname;
    }

    // In case we don't want to leave anything to doubt...
    //
    String systemHostname = EnvUtil.getSystemProperty(KETTLE_SYSTEM_HOSTNAME);
    if (!isEmpty(systemHostname)) {
        cachedHostname = systemHostname;
        return systemHostname;
    }

    String lastHostname = "localhost";
    try {
        Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
        while (en.hasMoreElements()) {
            NetworkInterface nwi = en.nextElement();
            Enumeration<InetAddress> ip = nwi.getInetAddresses();

            while (ip.hasMoreElements()) {
                InetAddress in = ip.nextElement();
                lastHostname = in.getHostName();
                // System.out.println("  ip address bound : "+in.getHostAddress());
                // System.out.println("  hostname         : "+in.getHostName());
                // System.out.println("  Cann.hostname    : "+in.getCanonicalHostName());
                // System.out.println("  ip string        : "+in.toString());
                if (!lastHostname.equalsIgnoreCase("localhost") && !(lastHostname.indexOf(':') >= 0)) {
                    break;
                }
            }
        }
    } catch (SocketException e) {
        // Eat exception, just return what you have
    }

    cachedHostname = lastHostname;

    return lastHostname;
}

From source file:org.apache.coyote.http11.Http11Processor.java

/**
 * Send an action to the connector.//from w w w. j  av  a2s .com
 * 
 * @param actionCode Type of the action
 * @param param Action parameter
 */
public void action(ActionCode actionCode, Object param) {

    if (actionCode == ActionCode.ACTION_COMMIT) {
        // Commit current response

        if (response.isCommitted())
            return;

        // Validate and write response headers
        prepareResponse();
        try {
            outputBuffer.commit();
        } catch (IOException e) {
            // Set error flag
            error = true;
        }

    } else if (actionCode == ActionCode.ACTION_ACK) {

        // Acknowlege request

        // Send a 100 status back if it makes sense (response not committed
        // yet, and client specified an expectation for 100-continue)

        if ((response.isCommitted()) || (!http11))
            return;

        MessageBytes expectMB = request.getMimeHeaders().getValue("expect");
        if ((expectMB != null) && (expectMB.indexOfIgnoreCase("100-continue", 0) != -1)) {
            try {
                outputBuffer.sendAck();
            } catch (IOException e) {
                // Set error flag
                error = true;
            }
        }

    } else if (actionCode == ActionCode.ACTION_CLIENT_FLUSH) {

        try {
            outputBuffer.flush();
        } catch (IOException e) {
            // Set error flag
            error = true;
            response.setErrorException(e);
        }

    } else if (actionCode == ActionCode.ACTION_CLOSE) {
        // Close

        // End the processing of the current request, and stop any further
        // transactions with the client

        try {
            outputBuffer.endRequest();
        } catch (IOException e) {
            // Set error flag
            error = true;
        }

    } else if (actionCode == ActionCode.ACTION_RESET) {

        // Reset response

        // Note: This must be called before the response is committed

        outputBuffer.reset();

    } else if (actionCode == ActionCode.ACTION_CUSTOM) {

        // Do nothing

    } else if (actionCode == ActionCode.ACTION_START) {

        started = true;

    } else if (actionCode == ActionCode.ACTION_STOP) {

        started = false;

    } else if (actionCode == ActionCode.ACTION_REQ_SSL_ATTRIBUTE) {

        try {
            if (sslSupport != null) {
                Object sslO = sslSupport.getCipherSuite();
                if (sslO != null)
                    request.setAttribute(SSLSupport.CIPHER_SUITE_KEY, sslO);
                sslO = sslSupport.getPeerCertificateChain(false);
                if (sslO != null)
                    request.setAttribute(SSLSupport.CERTIFICATE_KEY, sslO);
                sslO = sslSupport.getKeySize();
                if (sslO != null)
                    request.setAttribute(SSLSupport.KEY_SIZE_KEY, sslO);
                sslO = sslSupport.getSessionId();
                if (sslO != null)
                    request.setAttribute(SSLSupport.SESSION_ID_KEY, sslO);
            }
        } catch (Exception e) {
            log.warn("Exception getting SSL attributes ", e);
        }

    } else if (actionCode == ActionCode.ACTION_REQ_HOST_ADDR_ATTRIBUTE) {

        if ((remoteAddr == null) && (socket != null)) {
            InetAddress inetAddr = socket.getInetAddress();
            if (inetAddr != null) {
                remoteAddr = inetAddr.getHostAddress();
            }
        }
        request.remoteAddr().setString(remoteAddr);

    } else if (actionCode == ActionCode.ACTION_REQ_LOCAL_NAME_ATTRIBUTE) {

        if ((localName == null) && (socket != null)) {
            InetAddress inetAddr = socket.getLocalAddress();
            if (inetAddr != null) {
                localName = inetAddr.getHostName();
            }
        }
        request.localName().setString(localName);

    } else if (actionCode == ActionCode.ACTION_REQ_HOST_ATTRIBUTE) {

        if ((remoteHost == null) && (socket != null)) {
            InetAddress inetAddr = socket.getInetAddress();
            if (inetAddr != null) {
                remoteHost = inetAddr.getHostName();
            }
        }
        request.remoteHost().setString(remoteHost);

    } else if (actionCode == ActionCode.ACTION_REQ_LOCAL_ADDR_ATTRIBUTE) {

        if (localAddr == null)
            localAddr = socket.getLocalAddress().getHostAddress();

        request.localAddr().setString(localAddr);

    } else if (actionCode == ActionCode.ACTION_REQ_REMOTEPORT_ATTRIBUTE) {

        if ((remotePort == -1) && (socket != null)) {
            remotePort = socket.getPort();
        }
        request.setRemotePort(remotePort);

    } else if (actionCode == ActionCode.ACTION_REQ_LOCALPORT_ATTRIBUTE) {

        if ((localPort == -1) && (socket != null)) {
            localPort = socket.getLocalPort();
        }
        request.setLocalPort(localPort);

    } else if (actionCode == ActionCode.ACTION_REQ_SSL_CERTIFICATE) {
        if (sslSupport != null) {
            /*
             * Consume and buffer the request body, so that it does not
             * interfere with the client's handshake messages
             */
            InputFilter[] inputFilters = inputBuffer.getFilters();
            ((BufferedInputFilter) inputFilters[Constants.BUFFERED_FILTER]).setLimit(maxPostSize);
            inputBuffer.addActiveFilter(inputFilters[Constants.BUFFERED_FILTER]);
            try {
                Object sslO = sslSupport.getPeerCertificateChain(true);
                if (sslO != null) {
                    request.setAttribute(SSLSupport.CERTIFICATE_KEY, sslO);
                }
            } catch (Exception e) {
                log.warn("Exception getting SSL Cert", e);
            }
        }
    }

}

From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java

/**
 * This method is responsible for creating and sending a
 * 'nodeGainedService' event to Eventd/*from  w w  w.j a v  a  2 s  .c  o m*/
 *
 * @param nodeEntry Interface's parent node identifier.
 * @param ipAddr    Interface's IP address
 * @param svcName   Service name
 * @param qualifier Service qualifier (typically the port on which the service
 *                  was found)
 */
private void createAndSendNodeGainedServiceEvent(DbNodeEntry nodeEntry, InetAddress ipAddr, String svcName,
        String qualifier) {

    EventBuilder bldr = createEventBuilder(EventConstants.NODE_GAINED_SERVICE_EVENT_UEI);
    bldr.setNodeid(nodeEntry.getNodeId());
    bldr.setInterface(ipAddr);
    bldr.setService(svcName);
    bldr.addParam(EventConstants.PARM_IP_HOSTNAME, ipAddr.getHostName());
    bldr.addParam(EventConstants.PARM_NODE_LABEL, nodeEntry.getLabel());
    if (nodeEntry.getLabelSource() != null) {
        bldr.addParam(EventConstants.PARM_NODE_LABEL_SOURCE, nodeEntry.getLabelSource().toString());
    }
    // Add qualifier (if available)
    if (qualifier != null && qualifier.length() > 0) {
        bldr.addParam(EventConstants.PARM_QUALIFIER, qualifier);
    }

    // Add sysName (if available)
    if (nodeEntry.getSystemName() != null) {
        bldr.addParam(EventConstants.PARM_NODE_SYSNAME, nodeEntry.getSystemName());
    }

    // Add sysDescr (if available)
    if (nodeEntry.getSystemDescription() != null) {
        bldr.addParam(EventConstants.PARM_NODE_SYSDESCRIPTION, nodeEntry.getSystemDescription());
    }

    sendEvent(bldr.getEvent());
}

From source file:org.opennms.ng.services.capsd.SuspectEventProcessor.java

private void addSubIpInterfaces(Connection dbc, DbNodeEntry node, IfCollector collector, Date now, int nodeId,
        CapsdConfig cFactory, PollerConfig pollerCfgFactory, IfSnmpCollector snmpc) throws SQLException {

    if (!snmpc.hasIpAddrTable()) {
        return;/*from   ww  w  .j  av a2s.co  m*/
    }

    Map<InetAddress, List<IfCollector.SupportedProtocol>> extraTargets = collector.getAdditionalTargets();
    for (InetAddress xifaddr : extraTargets.keySet()) {

        LOG.debug("addInterfaces: adding interface {}", str(xifaddr));

        DbIpInterfaceEntry xipIfEntry = DbIpInterfaceEntry.create(nodeId, xifaddr);
        xipIfEntry.setLastPoll(now);
        xipIfEntry.setHostname(xifaddr.getHostName());

        /*
         * NOTE: (reference internal bug# 201) If the ip is 'managed', it
         * might still be 'not polled' based on the poller configuration.
         * The package filter evaluation requires that the ip be in the
         * database - at this point the ip is NOT in db, so insert as
         * active and update afterward. Try to avoid re-evaluating the ip
         * against filters for each service, try to get the first package
         * here and use that for service evaluation.
         */
        boolean xaddrUnmanaged = cFactory.isAddressUnmanaged(xifaddr);
        if (xaddrUnmanaged) {
            xipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_UNMANAGED);
        } else {
            xipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_MANAGED);
        }

        /*
         * Just set primary state to not eligible for now. The primary
         * SNMP interface won't be selected until after all interfaces
         * have been inserted into the database. This is because the
         * interface must already be in the database for filter rule
         * evaluation to succeed.
         */
        xipIfEntry.setPrimaryState(DbIpInterfaceEntry.SNMP_NOT_ELIGIBLE);
        int xifIndex = -1;
        if ((xifIndex = snmpc.getIfIndex(xifaddr)) != -1) {
            /*
             * XXX I'm not sure if it is always safe to call setIfIndex
             * here.  We should only do it if an snmpInterface entry
             * was previously created for this ifIndex.  It was likely done
             * by addSnmpInterfaces, but I have't checked to make sure that
             * all cases are covered. - dj@opennms.org
             */
            xipIfEntry.setIfIndex(xifIndex);
            int status = snmpc.getAdminStatus(xifIndex);
            if (status != -1) {
                xipIfEntry.setStatus(status);
            }

            if (!supportsSnmp(extraTargets.get(xifaddr))) {
                LOG.debug("addInterfaces: Interface doesn't support SNMP. {} set to not eligible",
                        str(xifaddr));
            }
        } else {
            /*
             * No ifIndex found so set primary state to NOT_ELIGIBLE
             */
            LOG.debug("addInterfaces: No ifIndex found. {} set to not eligible", str(xifaddr));
        }

        xipIfEntry.store(dbc);

        // now update if necessary
        org.opennms.netmgt.config.poller.Package xipPkg = null;
        if (!xaddrUnmanaged) {
            // The newly discoveried IP addr is not in the Package
            // IPList
            // Mapping yet, so rebuild the list.
            //
            pollerConfig.rebuildPackageIpListMap();

            boolean xipToBePolled = false;
            xipPkg = pollerCfgFactory.getFirstPackageMatch(str(xifaddr));
            if (xipPkg != null) {
                xipToBePolled = true;
            }

            if (!xipToBePolled) {
                // update ismanaged to 'N' in ipinterface
                xipIfEntry.setManagedState(DbIpInterfaceEntry.STATE_NOT_POLLED);
                xipIfEntry.store(dbc);
            }
        }

        // add the supported protocols
        addSupportedProtocols(node, xifaddr, extraTargets.get(xifaddr), xaddrUnmanaged, xifIndex, xipPkg);
    }
}