Example usage for java.net InetAddress getCanonicalHostName

List of usage examples for java.net InetAddress getCanonicalHostName

Introduction

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

Prototype

public String getCanonicalHostName() 

Source Link

Document

Gets the fully qualified domain name for this IP address.

Usage

From source file:com.moss.greenshell.wizard.catastrophe.PostMortemScreen.java

public static void submitErrorReport(final Throwable cause, final ErrorReportDecorator... decorators)
        throws Exception {

    List<ErrorReportChunk> chunks = new LinkedList<ErrorReportChunk>();

    try {//from   ww w  .  j a  v a 2s . co  m
        if (cause instanceof InternalErrorException) {
            InternalErrorException ie = (InternalErrorException) cause;
            ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                    ie.id().getBytes("UTF8"));
            chunks.add(chunk);
        } else if (cause instanceof SOAPFaultException) {
            SOAPFaultException soapFault = (SOAPFaultException) cause;
            String content = soapFault.getFault().getFirstChild().getTextContent();
            String prefix = "Internal Service Error Occurred: ";
            if (content.startsWith(prefix)) {
                String id = content.substring(prefix.length());
                ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                        id.getBytes("UTF8"));
                chunks.add(chunk);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }

    // STACK TRACE
    ByteArrayOutputStream stackBytes = new ByteArrayOutputStream();
    PrintStream stackPrintStream = new PrintStream(stackBytes);
    cause.printStackTrace(stackPrintStream);
    stackPrintStream.close();
    stackBytes.close();

    ErrorReportChunk chunk = new ErrorReportChunk("stack trace", "text/plain", stackBytes.toByteArray());
    chunks.add(chunk);

    // THREAD DUMP

    ByteArrayOutputStream dumpBytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(dumpBytes);
    Map<Thread, StackTraceElement[]> traceMap = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> next : traceMap.entrySet()) {
        out.println();
        out.println(next.getKey().getName());
        for (StackTraceElement line : next.getValue()) {
            String className = emptyIfNull(line.getClassName());
            String methodName = emptyIfNull(line.getMethodName());
            String fileName = emptyIfNull(line.getFileName());

            out.println("    " + className + "." + methodName + " (" + fileName + " line "
                    + line.getLineNumber() + ")");
        }
    }
    out.flush();
    out.close();
    ErrorReportChunk stackDump = new ErrorReportChunk("thread dump", "text/plain", dumpBytes.toByteArray());
    chunks.add(stackDump);

    // SYSTEM PROPERTIES
    ByteArrayOutputStream propsBytes = new ByteArrayOutputStream();
    PrintStream propsOut = new PrintStream(propsBytes);
    for (Map.Entry<Object, Object> next : System.getProperties().entrySet()) {
        propsOut.println(" " + next.getKey() + "=" + next.getValue());
    }
    propsOut.flush();
    propsOut.close();
    chunks.add(new ErrorReportChunk("system properties", "text/plain", propsBytes.toByteArray()));

    // LOCAL CLOCK
    chunks.add(new ErrorReportChunk("local clock", "text/plain", new DateTime().toString().getBytes()));

    // NETWORKING
    StringBuffer networking = new StringBuffer();
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        networking.append("INTERFACE: " + iface.getName() + " (" + iface.getDisplayName() + ")\n");
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            networking.append("  Address:" + address.getHostAddress() + "\n");
            networking.append("      Cannonical Host Name: " + address.getCanonicalHostName() + "\n");
            networking.append("                 Host Name: " + address.getHostName() + "\n");
        }
    }
    chunks.add(new ErrorReportChunk("network configuration", "text/plain", networking.toString().getBytes()));

    // DECORATORS
    if (decorators != null) {
        for (ErrorReportDecorator decorator : decorators) {
            chunks.addAll(decorator.makeChunks(cause));
        }
    }
    ErrorReport report = new ErrorReport(chunks);
    Reporter reporter = new Reporter();
    ReportId id = reporter.submitReport(report);
}

From source file:org.hyperic.plugin.vrealize.automation.VRAUtils.java

private static String getFqdnFromIp(String address) {
    InetAddress addr = null;
    try {//from   www . j a va2  s.co  m
        if (Pattern.matches(IPv4_ADDRESS_PATTERN, address) || Pattern.matches(IPv6_ADDRESS_PATTERN, address)) {

            addr = InetAddress.getByName(address);
            return addr.getCanonicalHostName();
        }
    } catch (Exception e) {
    }

    return null;
}

From source file:org.jkcsoft.java.util.JavaHelper.java

public static InetAddress getUsefulInetAddr() throws UnknownHostException {
    InetAddress returnInetAddr = InetAddress.getLocalHost();
    int usefulCount = 0;
    try {/* w  w  w. ja va2s .c  o  m*/
        Enumeration niEnum = NetworkInterface.getNetworkInterfaces();
        while (niEnum.hasMoreElements()) {
            NetworkInterface ni = (NetworkInterface) niEnum.nextElement();
            Enumeration ieEnum = ni.getInetAddresses();
            while (ieEnum.hasMoreElements()) {
                InetAddress inetAddr = InetAddress.getLocalHost();
                inetAddr = (InetAddress) ieEnum.nextElement();
                log.debug("NIC [" + ni.getDisplayName() + "]" + " Addr hn=[" + inetAddr.getHostName() + "]"
                        + " chn=[" + inetAddr.getCanonicalHostName() + "]" + " ha=[" + inetAddr.getHostAddress()
                        + "]");
                // hack to skip addresses often provided by Linux...
                if (!"127.0.0.1".equals(inetAddr.getHostAddress())
                        && inetAddr.getHostAddress().indexOf(':') == -1) {
                    if (usefulCount == 0)
                        returnInetAddr = inetAddr;
                    usefulCount++;
                } else {
                    // 
                }
            }
        }
    } catch (SocketException e) {
        log.error("getHostName", e);
    }

    if (usefulCount == 0) {
        log.warn("Only the loopback InetAddress could be found");
    }
    if (usefulCount > 1) {
        log.warn("More than one non-loopback InetAddrss was found; using the first one found.");
    }

    log.debug("Returning inet addr [" + returnInetAddr.toString() + "]");
    return returnInetAddr;
}

From source file:org.apache.hadoop.streaming.StreamUtil.java

static URL qualifyHost(URL url) {
    try {/*from   w  w  w .j a  va 2 s. c  o m*/
        InetAddress a = InetAddress.getByName(url.getHost());
        String qualHost = a.getCanonicalHostName();
        URL q = new URL(url.getProtocol(), qualHost, url.getPort(), url.getFile());
        return q;
    } catch (IOException io) {
        return url;
    }
}

From source file:org.opennms.provisiond.utils.CsvRequisitionParser.java

private static void createOrUpdateRequistion(RequisitionData rd) throws UnknownHostException {
    Requisition r = null;//from w w  w.  ja v  a  2 s  .c  o  m
    RequisitionNode rn = new RequisitionNode();
    String foreignSource = rd.getForeignSource();

    r = m_fsr.getRequisition(foreignSource);

    if (r == null) {
        r = new Requisition(foreignSource);
    }

    System.err.println("Creating/Updating requistion: " + foreignSource);

    r.updateDateStamp();

    RequisitionMonitoredServiceCollection services = new RequisitionMonitoredServiceCollection();
    for (String svc : m_serviceList) {
        services.add(new RequisitionMonitoredService(svc));
    }

    RequisitionInterface iface = new RequisitionInterface();
    iface.setDescr("mgmt-if");
    iface.setIpAddr(rd.getPrimaryIp());
    iface.setManaged(true);
    iface.setSnmpPrimary(PrimaryType.PRIMARY);
    iface.setStatus(Integer.valueOf(1));
    iface.setMonitoredServices(services.getObjects());

    RequisitionInterfaceCollection ric = new RequisitionInterfaceCollection();
    ric.add(iface);

    //add categories requisition level categories
    RequisitionCategoryCollection rcc = new RequisitionCategoryCollection();
    if (m_categoryList != null && m_categoryList.size() > 0) {
        for (String cat : m_categoryList) {
            rcc.add(new RequisitionCategory(cat));
        }
    }

    //add categories already on the node to the requisition
    if (rd.getCategories() != null) {
        for (String cat : rd.getCategories()) {
            rcc.add(new RequisitionCategory(cat));
        }
    }

    rn.setBuilding(foreignSource);

    if (rcc.size() >= 1) {
        rn.setCategories(rcc.getObjects());
    }

    rn.setForeignId(rd.getForeignId());
    rn.setInterfaces(ric.getObjects());

    String nodeLabel = rd.getNodeLabel();
    if (m_resolveIps) {
        InetAddress addr = InetAddress.getByName(rd.getPrimaryIp());
        nodeLabel = addr.getCanonicalHostName();
    }

    rn.setNodeLabel(nodeLabel);

    //r.insertNode(rn);
    r.putNode(rn);
    m_fsr.save(r);
}

From source file:org.apache.hadoop.net.DNS.java

/**
 * Returns all the host names associated by the provided nameserver with the
 * address bound to the specified network interface
 *
 * @param strInterface/*ww w .  j a v a 2s  .  c  o m*/
 *            The name of the network interface or subinterface to query
 *            (e.g. eth0 or eth0:0)
 * @param nameserver
 *            The DNS host name
 * @param tryfallbackResolution
 *            if true and if reverse DNS resolution fails then attempt to
 *            resolve the hostname with
 *            {@link InetAddress#getCanonicalHostName()} which includes
 *            hosts file resolution.
 * @return A string vector of all host names associated with the IPs tied to
 *         the specified interface
 * @throws UnknownHostException if the given interface is invalid
 */
public static String[] getHosts(String strInterface, @Nullable String nameserver, boolean tryfallbackResolution)
        throws UnknownHostException {
    final List<String> hosts = new Vector<String>();
    final List<InetAddress> addresses = getIPsAsInetAddressList(strInterface, true);
    for (InetAddress address : addresses) {
        try {
            hosts.add(reverseDns(address, nameserver));
        } catch (NamingException ignored) {
        }
    }
    if (hosts.isEmpty() && tryfallbackResolution) {
        for (InetAddress address : addresses) {
            final String canonicalHostName = address.getCanonicalHostName();
            // Don't use the result if it looks like an IP address.
            if (!InetAddresses.isInetAddress(canonicalHostName)) {
                hosts.add(canonicalHostName);
            }
        }
    }

    if (hosts.isEmpty()) {
        LOG.warn("Unable to determine hostname for interface " + strInterface);
        hosts.add(cachedHostname);
    }
    return hosts.toArray(new String[hosts.size()]);
}

From source file:stargate.commons.utils.IPUtils.java

public static Collection<String> getHostAddress() {
    if (!cached_host_addr.isEmpty()) {
        return Collections.unmodifiableCollection(cached_host_addr);
    } else {/* ww w . j  a  v a  2  s  .  co  m*/
        try {
            Enumeration e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface n = (NetworkInterface) e.nextElement();
                Enumeration ee = n.getInetAddresses();
                while (ee.hasMoreElements()) {
                    InetAddress i = (InetAddress) ee.nextElement();

                    String hostAddress = i.getHostAddress();
                    if (isProperHostAddress(hostAddress)) {
                        if (!cached_host_addr.contains(hostAddress)) {
                            cached_host_addr.add(hostAddress);
                        }
                    }

                    String hostName = i.getHostName();
                    if (isProperHostAddress(hostName)) {
                        if (!cached_host_addr.contains(hostName)) {
                            cached_host_addr.add(hostName);
                        }
                    }

                    String canonicalHostName = i.getCanonicalHostName();
                    if (isProperHostAddress(canonicalHostName)) {
                        if (!cached_host_addr.contains(canonicalHostName)) {
                            cached_host_addr.add(canonicalHostName);
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            LOG.error("Exception occurred while scanning local interfaces", ex);
        }

        return Collections.unmodifiableCollection(cached_host_addr);
    }
}

From source file:com.datatorrent.stram.client.StramClientUtils.java

public static String getSocketConnectString(InetSocketAddress socketAddress) {
    String host;//  www. jav  a2 s . c om
    InetAddress address = socketAddress.getAddress();
    if (address == null) {
        host = socketAddress.getHostString();
    } else if (address.isAnyLocalAddress() || address.isLoopbackAddress()) {
        host = address.getCanonicalHostName();
    } else {
        host = address.getHostName();
    }
    return host + ":" + socketAddress.getPort();
}

From source file:hsyndicate.utils.IPUtils.java

public static Collection<String> getHostAddress() {
    if (!cachedHostAddr.isEmpty()) {
        return Collections.unmodifiableCollection(cachedHostAddr);
    } else {//from  w  w  w . ja v a2s.c o  m
        try {
            Enumeration e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface n = (NetworkInterface) e.nextElement();
                Enumeration ee = n.getInetAddresses();
                while (ee.hasMoreElements()) {
                    InetAddress i = (InetAddress) ee.nextElement();

                    String hostAddress = i.getHostAddress();
                    if (isProperHostAddress(hostAddress)) {
                        if (!cachedHostAddr.contains(hostAddress)) {
                            cachedHostAddr.add(hostAddress);
                        }
                    }

                    String hostName = i.getHostName();
                    if (isProperHostAddress(hostName)) {
                        if (!cachedHostAddr.contains(hostName)) {
                            cachedHostAddr.add(hostName);
                        }
                    }

                    String canonicalHostName = i.getCanonicalHostName();
                    if (isProperHostAddress(canonicalHostName)) {
                        if (!cachedHostAddr.contains(canonicalHostName)) {
                            cachedHostAddr.add(canonicalHostName);
                        }
                    }
                }
            }
        } catch (SocketException ex) {
            LOG.error("Exception occurred while scanning local interfaces", ex);
        }

        return Collections.unmodifiableCollection(cachedHostAddr);
    }
}

From source file:com.buaa.cfs.utils.SecurityUtil.java

/**
 * Convert Kerberos principal name pattern to valid Kerberos principal names. This method is similar to {@link
 * #getServerPrincipal(String, String)}, except 1) the reverse DNS lookup from addr to hostname is done only when
 * necessary, 2) param addr can't be null (no default behavior of using local hostname when addr is null).
 *
 * @param principalConfig Kerberos principal name pattern to convert
 * @param addr            InetAddress of the host used for substitution
 *
 * @return converted Kerberos principal name
 *
 * @throws IOException if the client address cannot be determined
 *///w ww  .jav  a2  s .c  o  m
public static String getServerPrincipal(String principalConfig, InetAddress addr) throws IOException {
    String[] components = getComponents(principalConfig);
    if (components == null || components.length != 3 || !components[1].equals(HOSTNAME_PATTERN)) {
        return principalConfig;
    } else {
        if (addr == null) {
            throw new IOException(
                    "Can't replace " + HOSTNAME_PATTERN + " pattern since client address is null");
        }
        return replacePattern(components, addr.getCanonicalHostName());
    }
}