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.sf.mpaxs.spi.server.settings.Settings.java

private static String getOwnIP() {

    InetAddress inet2 = null;/*from  ww w. ja v a  2 s  .  co  m*/
    try {
        InetAddress inet1 = InetAddress.getLocalHost();
        inet2 = InetAddress.getByName(inet1.getHostName());
        return inet2.getHostAddress();
    } catch (UnknownHostException ex) {
        Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:net.grinder.util.NetworkUtils.java

/**
 * Get local host name by connecting to a server.
 *
 * @param byConnecting the server address to connect.
 * @param port         the port to connect
 * @return localhost name. if fails, return "localhost"
 *//*from  w ww  .j av a  2s. c  o  m*/
static String getLocalHostName(String byConnecting, int port) {
    InetAddress addr = getLocalInetAddress(byConnecting, port);
    if (addr != null) {
        return addr.getHostName();
    } else {
        return "localhost";
    }
}

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 {/* www .ja v  a2  s. com*/
        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:ac.dynam.rundeck.plugin.resources.ovirt.InstanceToNodeMapper.java

/**
 * Convert an oVirt Instance to a RunDeck INodeEntry based on the mapping input
 *//*from  w w w.  jav  a2s  .  c  om*/
@SuppressWarnings("unchecked")
static INodeEntry instanceToNode(final VM inst) throws GeneratorException {
    final NodeEntryImpl node = new NodeEntryImpl();

    node.setNodename(inst.getName());
    node.setOsArch(inst.getCpu().getArchitecture());
    node.setOsName(inst.getOs().getType());
    node.setDescription(inst.getDescription());
    node.setUsername("root");
    InetAddress address = null;
    if (inst.getGuestInfo() != null) {
        try {
            address = InetAddress.getByName(inst.getGuestInfo().getFqdn());
            logger.debug("Host " + node.getNodename() + " Guest FQDN " + inst.getGuestInfo().getFqdn()
                    + " Address: " + address.getHostName());
            if (address.getHostName() == "localhost")
                throw new UnknownHostException();
        } catch (UnknownHostException e) {
            /* try the first IP instead then */
            logger.warn("Host " + node.getNodename() + " address " + inst.getGuestInfo().getFqdn()
                    + " does not resolve. Trying IP addresses instead");
            for (int i = 0; i < inst.getGuestInfo().getIps().getIPs().size(); i++) {
                logger.debug("Host " + node.getNodename() + " Trying "
                        + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                try {
                    address = InetAddress.getByName(inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                    if (address != null) {
                        if (address.isLinkLocalAddress() || address.isMulticastAddress()) {
                            logger.warn("Host " + node.getNodename() + " ip address is not valid: "
                                    + inst.getGuestInfo().getIps().getIPs().get(i).getAddress());
                            continue;
                        }
                        logger.debug("Host " + node.getNodename() + " ip address " + address.getHostAddress()
                                + " will be used instead");
                        break;
                    }
                } catch (UnknownHostException e1) {
                    logger.warn("Host " + node.getNodename() + " IP Address "
                            + inst.getGuestInfo().getIps().getIPs().get(i).getAddress() + " is invalid");
                }
            }
        }
    }
    if (address == null) {
        /* try resolving based on name */
        try {
            address = InetAddress.getByName(node.getNodename());
        } catch (UnknownHostException e) {
            logger.warn("Unable to Find IP address for Host " + node.getNodename());
            return null;
        }
    }

    if (address != null)
        node.setHostname(address.getCanonicalHostName());

    if (inst.getTags() != null) {
        VMTags tags = inst.getTags();
        final HashSet<String> tagset = new HashSet<String>();
        try {
            for (int j = 0; j < tags.list().size(); j++) {
                tagset.add(tags.list().get(j).getName());
            }
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (null == node.getTags()) {
            node.setTags(tagset);
        } else {
            final HashSet<String> orig = new HashSet<String>(node.getTags());
            orig.addAll(tagset);
            node.setTags(orig);
        }
    }

    if (inst.getHighAvailability().getEnabled())
        node.setAttribute("HighAvailability", "true");
    if (inst.getType() != null)
        node.setAttribute("Host Type", inst.getType());
    node.setAttribute("oVirt VM", "true");
    node.setAttribute("oVirt Host", inst.getHost().getName());

    return node;
}

From source file:org.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java

static Credentials getCredentials(final String username, final String password, final InetAddress address,
        boolean forceUserNamePassword) {
    int i = username.indexOf("\\"); //$NON-NLS-1$
    if (i > 0 && i < username.length() - 1 && address != null && !forceUserNamePassword) {
        String hostName = address.getHostName();
        try {//from  w  ww .j a v  a 2 s . c o m
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost != null) {
                hostName = localHost.getHostName();
            }
        } catch (UnknownHostException e) {
            StatusHandler.log(new Status(IStatus.ERROR, ID_PLUGIN,
                    "Unable to get hostname.  Defaulting to servers host.", e)); //$NON-NLS-1$
        }
        if (hostName == null) {
            hostName = address.getHostName();
        }
        return new NTCredentials(username.substring(i + 1), password, hostName, username.substring(0, i));
    } else {
        return new UsernamePasswordCredentials(username, password);
    }
}

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 {/*from  w w  w . jav  a 2  s .  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 (!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:org.elasticsearch.hadoop.util.ecs.HostData.java

private static HostData collectHostData() {
    String osName = getPropOrNull("os.name");
    String osVersion = getPropOrNull("os.version");
    String osArch = getPropOrNull("os.arch");

    InetAddress localAddress;
    try {//from   ww  w.  j a  v  a2s.com
        localAddress = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        // Swallow and set the host info to null;
        LOG.warn("Could not collect host information for error tracing. Continuing with null host info.", e);
        localAddress = null;
    }

    String hostName;
    String hostip;
    if (localAddress != null) {
        hostName = localAddress.getHostName();
        hostip = localAddress.getHostAddress();
    } else {
        hostName = null;
        hostip = null;
    }

    Long hostTz = TimeUnit.SECONDS.convert(TimeZone.getDefault().getRawOffset(), TimeUnit.MILLISECONDS);

    return new HostData(hostName, hostip, hostTz, osName, osVersion, osArch);
}

From source file:com.lm.lic.manager.util.GenUtil.java

/**
 * @param request/*  ww  w. j  av a 2  s . c  o m*/
 * @return
 */
public static String findDomain(HttpServletRequest request) {
    String domain = null;
    String remoteHost = request.getRemoteHost();
    try {
        InetAddress inetAddress = Inet4Address.getByName(remoteHost);
        domain = inetAddress.getHostName();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    return domain;
}

From source file:org.alfresco.repo.action.ActionTrackingServiceImpl.java

/**
 * Builds up the details to be stored in a cache for a specific action
 *///from   www  .j  a v  a2  s  .co  m
protected static ExecutionDetails buildExecutionDetails(Action action, NodeRef actionedUponNodeRef) {
    // Where are we running?
    if (machineName == null) {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            machineName = localhost.getHostAddress() + " : " + localhost.getHostName();
        } catch (UnknownHostException e) {
            machineName = "(machine details unavailable - server IP not known)";
        }
    }

    // Generate
    return new ExecutionDetails(buildExecutionSummary(action), action.getNodeRef(), actionedUponNodeRef,
            machineName, action.getExecutionStartDate(), false);
}

From source file:org.apache.synapse.util.DataSourceRegistrar.java

/**
 * Register data sources in the JNDI context
 * Given properties should contains all the properties need for construct JNDI naming references
 *
 * @param dsProperties The source properties
 *///from www .j av  a2 s.  c om
public static void registerDataSources(Properties dsProperties) {

    if (dsProperties == null) {
        if (log.isDebugEnabled()) {
            log.debug("DataSource properties cannot be found..");
        }
        return;
    }

    String dataSources = getProperty(dsProperties, SynapseConstants.SYNAPSE_DATASOURCES, null);

    if (dataSources == null || "".equals(dataSources)) {
        if (log.isDebugEnabled()) {
            log.debug("No DataSources defined for initialization..");
        }
        return;
    }

    String[] dataSourcesNames = dataSources.split(",");
    if (dataSourcesNames == null || dataSourcesNames.length == 0) {
        if (log.isDebugEnabled()) {
            log.debug("No DataSource definitions found for initialization..");
        }
        return;
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append(SynapseConstants.SYNAPSE_DATASOURCES);
    buffer.append(DOT_STRING);
    // The prefix for root level properties
    String rootPrefix = buffer.toString();

    // setting naming provider
    Hashtable props = new Hashtable();
    Properties jndiEvn = new Properties(); //This is needed for PerUserPoolDatasource

    String namingFactory = getProperty(dsProperties, rootPrefix + PROP_ICFACTORY,
            "com.sun.jndi.rmi.registry.RegistryContextFactory");

    props.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);
    jndiEvn.put(Context.INITIAL_CONTEXT_FACTORY, namingFactory);

    String providerHost = "localhost";
    try {
        InetAddress addr = InetAddress.getLocalHost();
        if (addr != null) {
            String hostname = addr.getHostName();
            if (hostname == null) {
                String ipAddr = addr.getHostAddress();
                if (ipAddr != null) {
                    providerHost = ipAddr;
                }
            } else {
                providerHost = hostname;
            }
        }
    } catch (UnknownHostException e) {
        log.warn("Unable to determine hostname or IP address.. Using localhost", e);
    }

    // default port for RMI registry
    int port = 2199;
    String providerPort = getProperty(dsProperties, rootPrefix + PROP_PROVIDER_PORT, String.valueOf(port));
    try {
        port = Integer.parseInt(providerPort);
    } catch (NumberFormatException ignored) {
    }

    // Create a RMI local registry
    RMIRegistryController.getInstance().createLocalRegistry(port);

    String providerUrl = getProperty(dsProperties, rootPrefix + PROP_PROVIDER_URL,
            "rmi://" + providerHost + ":" + providerPort);

    props.put(Context.PROVIDER_URL, providerUrl);
    jndiEvn.put(Context.PROVIDER_URL, providerUrl);

    log.info("DataSources will be registered in the JNDI context with provider PROP_URL : " + providerUrl);

    try {
        InitialContext initialContext = new InitialContext(props);
        //Registering data sources with the initial context
        for (int i = 0; i < dataSourcesNames.length; i++) {
            registerDataSource(dataSourcesNames[i], dsProperties, initialContext, jndiEvn);
        }

    } catch (NamingException e) {
        String msg = "Error constructing an InitialContext to register DataSources";
        handleException(msg, e);
    }
}