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:voldemort.server.VoldemortServer.java

/**
 * Compare the configured hostname with all the ip addresses and hostnames
 * for the server node, and log a warning if there is a mismatch.
 *
 *//*from w  w w .  j a v  a2s .  com*/
// TODO: VoldemortServer should throw exception if cluster xml, node id, and
// server's state are not all mutually consistent.
//
// "I attempted to do this in the past. In practice its hard since the
// hostname strings returned may not exactly match what's in cluster.xml
// (ela4-app0000.prod vs ela4-app0000.prod.linkedin.com). And for folks
// running with multiple interfaces and stuff in the open source world, not
// sure how it would fan out..
//
// I am in favour of doing this though.. May be implement a server config,
// "strict.hostname.check.on.startup" which is false by default and true for
// our environments and our SRE makes sure there is an exact match?" --
// VChandar
//
// "Strict host name doesn't work? We can always trim the rest before the comparison."
// -- LGao
private void checkHostName() {
    try {
        HashSet<String> ipAddrList = new HashSet<String>();
        InetAddress localhost = InetAddress.getLocalHost();
        InetAddress[] serverAddrs = InetAddress.getAllByName(localhost.getCanonicalHostName());

        ipAddrList.add("localhost");
        if (serverAddrs != null && serverAddrs.length > 0) {
            for (InetAddress addr : serverAddrs) {
                if (addr.getHostName() != null)
                    ipAddrList.add(addr.getHostName());
                if (addr.getHostAddress() != null)
                    ipAddrList.add(addr.getHostAddress());
                if (addr.getCanonicalHostName() != null)
                    ipAddrList.add(addr.getCanonicalHostName());
            }
        }
        if (!ipAddrList.contains(this.identityNode.getHost())) {
            logger.info("List of all IPs & Hostnames for the current node:" + ipAddrList);
            logger.info("Configured hostname [" + this.identityNode.getHost()
                    + "] does not seem to match current node.");
        }
    } catch (UnknownHostException uhe) {
        logger.warn("Unable to obtain IP information for current node", uhe);
    } catch (SecurityException se) {
        logger.warn("Security Manager does not permit obtaining IP Information", se);
    }
}

From source file:com.jpeterson.littles3.S3ObjectRequestTest.java

/**
 * Integration test to execute the algorithm for hostname resolution.
 *///  www.j  ava 2 s . c  om
public void xtest_localHost() {
    String configHost;
    String token = "$resolvedLocalHost$";

    configHost = "foo:" + token + token + ":8080";

    if (configHost.indexOf(token) >= 0) {
        InetAddress localHost;
        String resolvedLocalHost = "localhost";

        try {
            localHost = InetAddress.getLocalHost();
            resolvedLocalHost = localHost.getCanonicalHostName();
        } catch (UnknownHostException e) {
            logger.fatal("Unable to resolve local host", e);
        }

        configHost = configHost.replace(token, resolvedLocalHost);
    }

    // this is machine dependent
    System.out.println(">>>> configHost: " + configHost);
    assertEquals("Unexpected hostname", "foo:PEM32Z2RC1LIC.NCSP.PEROOT.COMPEM32Z2RC1LIC.NCSP.PEROOT.COM:8080",
            configHost);
}

From source file:org.archive.crawler.writer.WARCWriterProcessor.java

/**
 * Return relevant values as header-like fields (here ANVLRecord, but 
 * spec-defined "application/warc-fields" type when written). Field
 * names from from DCMI Terms and the WARC/0.17 specification.
 * //from www. jav  a  2s. c  o  m
 * @see org.archive.crawler.framework.WriterPoolProcessor#getFirstrecordBody(java.io.File)
 */
@Override
protected String getFirstrecordBody(File orderFile) {
    ANVLRecord record = new ANVLRecord(7);
    record.addLabelValue("software", "Heritrix/" + Heritrix.getVersion() + " http://crawler.archive.org");
    try {
        InetAddress host = InetAddress.getLocalHost();
        record.addLabelValue("ip", host.getHostAddress());
        record.addLabelValue("hostname", host.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.log(Level.WARNING, "unable top obtain local crawl engine host", e);
    }

    // conforms to ISO 28500:2009 as of May 2009
    // as described at http://bibnum.bnf.fr/WARC/ 
    // latest draft as of November 2008
    record.addLabelValue("format", "WARC File Format 1.0");
    record.addLabelValue("conformsTo", "http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf");

    // Get other values from order.xml 
    try {
        Document doc = XmlUtils.getDocument(orderFile);
        addIfNotBlank(record, "operator", XmlUtils.xpathOrNull(doc, "//meta/operator"));
        addIfNotBlank(record, "publisher", XmlUtils.xpathOrNull(doc, "//meta/organization"));
        addIfNotBlank(record, "audience", XmlUtils.xpathOrNull(doc, "//meta/audience"));
        addIfNotBlank(record, "isPartOf", XmlUtils.xpathOrNull(doc, "//meta/name"));

        // disabling "created" field per HER-1634
        // though it's theoretically useful as a means of distinguishing 
        // one crawl from another, the current usage/specification is too 
        // vague... in particular a 'created' field in the 'warcinfo' is 
        // reasonable to interpret as applying to the WARC-unit, rather 
        // than the crawl-job-unit so we remove it and see if anyone 
        // complains or makes a case for restoring it in a less-ambiguous 
        // manner
        //            String rawDate = XmlUtils.xpathOrNull(doc,"//meta/date");
        //            if(StringUtils.isNotBlank(rawDate)) {
        //               Date date;
        //               try {
        //                  date = ArchiveUtils.parse14DigitDate(rawDate);
        //                  addIfNotBlank(record,"created",ArchiveUtils.getLog14Date(date));
        //               } catch (ParseException e) {
        //                  logger.log(Level.WARNING,"obtaining warc created date",e);
        //               }
        //            }

        addIfNotBlank(record, "description", XmlUtils.xpathOrNull(doc, "//meta/description"));
        addIfNotBlank(record, "robots",
                XmlUtils.xpathOrNull(doc, "//newObject[@name='robots-honoring-policy']/string[@name='type']"));
        addIfNotBlank(record, "http-header-user-agent",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='user-agent']"));
        addIfNotBlank(record, "http-header-from",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='from']"));
    } catch (IOException e) {
        logger.log(Level.WARNING, "obtaining warcinfo", e);
    }
    // really ugly to return as string, when it may just be merged with 
    // a couple other fields at write time, but changing would require 
    // larger refactoring
    return record.toString();
}

From source file:org.rhq.helpers.rtfilter.filter.RtFilter.java

/**
 * Open the logfile for the given serverName. If serverName is localhost, then no
 * vhost portion is added to the logfile name. Otherwise the logfile name is
 * prefix + vhost + "_" + contextRoot + "_rt.log"<br/>
 * E.g. '/devel/jboss-4.0.3SP1/server/default/log/rt/snert.home.bsd.de_test_rt.log'.
 * <br/>/*from  ww  w  .j  a  v  a  2  s .c om*/
 * After opening the file we open a writer where we send results to. If
 * opening fails, no exceptions are thrown, as throwing any exception would cause the associated webapp to
 * fail to deploy - not something we ever want to do. Instead, the filter will simply not try to process any
 * requests (i.e. doFilter() will call the rest of the filter chain, and then just return).
 * <p/>
 * This method will set the fileDone variable to true upon success.<br/>
 * This method will set the initialized variable to false upon failure.<br/>
 * @param serverName Name of the virtual host
 */
private void openFile(String serverName) {
    String vhost = "";
    boolean found = false;

    if ("localhost".equals(serverName) || "127.0.0.1".equals(serverName)) {
        vhost = "";
        found = true;
    }

    // try to see if the user provided a mapping for this server name
    if (!found && vhostMappings.containsKey(serverName)) {
        found = true;
        vhost = vhostMappings.getProperty(serverName);
        if (vhost == null || vhost.equals(""))
            vhost = ""; // It is in the mapping, but no value set -> no vhost
        else
            vhost += "_"; // Otherwise take it and append the separator
        if (log.isDebugEnabled())
            log.debug("Vhost determined from mapping >" + vhost + "<");
    }

    // check server name against hostname and hostname.fqdn an see if they match
    if (!found && vhostMappings.containsKey(HOST_TOKEN)) {
        vhost = vhostMappings.getProperty(HOST_TOKEN);
        if (myHostName.startsWith(serverName) || myCHostName.startsWith(serverName)) {
            // Match, so take the mapping from the file
            if (vhost == null || vhost.equals("")) {
                vhost = ""; // It is in the mapping, but no value set -> no vhost
            } else {
                vhost += "_"; // Otherwise take it and append the separator
            }
            found = true;
            if (log.isDebugEnabled())
                log.debug("Vhost determined from %HOST% token >" + vhost + "<");
        }
    }

    if (!found) {
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost.getHostName().equalsIgnoreCase(serverName)
                    || localHost.getCanonicalHostName().equalsIgnoreCase(serverName)
                    || localHost.getHostAddress().equals(serverName)) {
                vhost = "";
                found = true;
            }
        } catch (Exception e) {
            found = false;
        }
    }

    // Nothing found? Fall back to serverName + _ as prefix
    if (!found) {
        vhost = serverName + "_"; // Not found in mapping? Take it literal + separator
    }

    // if this is a sub-context (e.g. news/radio), then replace the / by a _ to
    // prevent interpretation of the / as a dir separator.
    String contextFileName = contextName.replace('/', '_');

    String logFileName = this.logFilePrefix + vhost + contextFileName + "_rt.log";
    this.logFile = new File(this.logDirectory, logFileName);
    log.info("-- Filter openFile: Writing response-time log for webapp with context root '" + this.contextName
            + "' to '" + this.logFile + "' (hashCode=" + hashCode() + ")...");
    boolean append = true;
    try {
        openFileWriter(append);
        fileDone = true;
    } catch (Exception e) {
        // reset the initialized flag in case of error
        this.initialized = false;
        log.warn(e.getMessage());
    }

}

From source file:org.tango.server.ServerManager.java

/**
 * WARNING: it is jvm dependent (works for sun')
 *
 * @throws DevFailed//from  w w  w.ja  v a 2  s .c o m
 */
private void initPIDAndHostName() throws DevFailed {

    final RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
    final String pidAndHost = rmxb.getName();
    final String[] splitted = pidAndHost.split("@");
    if (splitted.length > 1) {
        pid = splitted[0];
    }

    try {
        final InetAddress addr;
        if (ORBManager.OAI_ADDR != null && !ORBManager.OAI_ADDR.isEmpty()) {
            addr = InetAddress.getByName(ORBManager.OAI_ADDR);
        } else {
            addr = InetAddress.getLocalHost();
        }
        hostName = addr.getCanonicalHostName();
    } catch (final UnknownHostException e) {
        DevFailedUtils.throwDevFailed(e);
    }

    logger.debug("pid: " + pid);
    logger.debug("hostName: " + hostName);

}

From source file:org.apache.jmeter.util.JMeterUtils.java

private static void getLocalHostDetails() {
    InetAddress localHost = null;
    try {/*ww  w  .j  a v  a  2 s  . c  o  m*/
        localHost = InetAddress.getLocalHost();
    } catch (UnknownHostException e1) {
        log.error("Unable to get local host IP address.", e1);
        return; // TODO - perhaps this should be a fatal error?
    }
    localHostIP = localHost.getHostAddress();
    localHostName = localHost.getHostName();
    localHostFullName = localHost.getCanonicalHostName();
}

From source file:org.apache.hadoop.realtime.server.DragonApplicationMaster.java

private RegisterApplicationMasterResponse registerToRM() throws YarnRemoteException, UnknownHostException {
    InetAddress host = InetAddress.getLocalHost();

    RegisterApplicationMasterRequest appMasterRequest = Records
            .newRecord(RegisterApplicationMasterRequest.class);

    appMasterRequest.setApplicationAttemptId(appAttemptID);
    appMasterRequest.setHost(host.getCanonicalHostName());
    appMasterRequest.setRpcPort(9999);// w ww.j  av  a  2  s  .  com
    appMasterRequest.setTrackingUrl(host.getCanonicalHostName() + ":" + 9999);

    return resourceManager.registerApplicationMaster(appMasterRequest);
}

From source file:org.wso2.andes.server.Broker.java

/**
 * Starts the TCP listener for handling AMQP messages.
 *
 * @param config       The configuration for application registry.
 * @param options      Broker options//from w w w .  jav a2 s .c o m
 * @param serverConfig Server configuration
 * @throws AndesException
 */
private void startAMQPListener(ApplicationRegistry config, BrokerOptions options,
        ServerConfiguration serverConfig) throws AndesException {
    try {
        if (AndesConfigurationManager.<Boolean>readValue(AndesConfiguration.TRANSPORTS_AMQP_ENABLED)) {
            ConfigurationManagementMBean configMBean = new ConfigurationManagementMBean();
            configMBean.register();

            ServerInformationMBean sysInfoMBean = new ServerInformationMBean(config);
            sysInfoMBean.register();

            Set<Integer> ports = new HashSet<Integer>(options.getPorts());
            if (ports.isEmpty()) {
                parsePortList(ports, serverConfig.getPorts());
            }

            Set<Integer> sslPorts = new HashSet<Integer>(options.getSSLPorts());
            if (sslPorts.isEmpty()) {
                parsePortList(sslPorts, serverConfig.getSSLPorts());
            }

            Set<Integer> exclude_0_10 = new HashSet<Integer>(options.getExcludedPorts(ProtocolExclusion.v0_10));
            if (exclude_0_10.isEmpty()) {
                parsePortList(exclude_0_10, serverConfig.getPortExclude010());
            }

            Set<Integer> exclude_0_9_1 = new HashSet<Integer>(
                    options.getExcludedPorts(ProtocolExclusion.v0_9_1));
            if (exclude_0_9_1.isEmpty()) {
                parsePortList(exclude_0_9_1, serverConfig.getPortExclude091());
            }

            Set<Integer> exclude_0_9 = new HashSet<Integer>(options.getExcludedPorts(ProtocolExclusion.v0_9));
            if (exclude_0_9.isEmpty()) {
                parsePortList(exclude_0_9, serverConfig.getPortExclude09());
            }

            Set<Integer> exclude_0_8 = new HashSet<Integer>(options.getExcludedPorts(ProtocolExclusion.v0_8));
            if (exclude_0_8.isEmpty()) {
                parsePortList(exclude_0_8, serverConfig.getPortExclude08());
            }

            String bindAddressFromBrokerOptions = options.getBind();
            if (null == bindAddressFromBrokerOptions) {
                bindAddressFromBrokerOptions = serverConfig.getBind();
            }

            InetAddress bindAddressForHostname;
            if (WILDCARD_ADDRESS.equals(bindAddressFromBrokerOptions)) {
                bindAddressForHostname = new InetSocketAddress(0).getAddress();
            } else {
                bindAddressForHostname = InetAddress.getByName(bindAddressFromBrokerOptions);
            }
            String hostName = bindAddressForHostname.getCanonicalHostName();

            if (!serverConfig.getSSLOnly()) {
                for (int port : ports) {
                    Set<AmqpProtocolVersion> supported = EnumSet.allOf(AmqpProtocolVersion.class);

                    if (exclude_0_10.contains(port)) {
                        supported.remove(AmqpProtocolVersion.v0_10);
                    }

                    if (exclude_0_9_1.contains(port)) {
                        supported.remove(AmqpProtocolVersion.v0_9_1);
                    }
                    if (exclude_0_9.contains(port)) {
                        supported.remove(AmqpProtocolVersion.v0_9);
                    }
                    if (exclude_0_8.contains(port)) {
                        supported.remove(AmqpProtocolVersion.v0_8);
                    }

                    NetworkTransportConfiguration settings = new ServerNetworkTransportConfiguration(
                            serverConfig, port, bindAddressFromBrokerOptions, Transport.TCP);

                    IncomingNetworkTransport transport = Transport.getIncomingTransportInstance();
                    MultiVersionProtocolEngineFactory protocolEngineFactory = new MultiVersionProtocolEngineFactory(
                            hostName, supported);

                    transport.accept(settings, protocolEngineFactory, null);
                    ApplicationRegistry.getInstance().addAcceptor(
                            new InetSocketAddress(bindAddressForHostname, port),
                            new QpidAcceptor(transport, "TCP"));
                    CurrentActor.get().message(BrokerMessages.LISTENING("TCP", port));

                }
            }

            if (serverConfig.getEnableSSL()) {
                JKSStore keyStore = AndesConfigurationManager
                        .readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_KEYSTORE);
                JKSStore trustStore = AndesConfigurationManager
                        .readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_TRUSTSTORE);

                String sslProtocols = AndesConfigurationManager
                        .readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_PROTOCOLS);
                String ciphers = AndesConfigurationManager
                        .readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_CIPHERS);

                SSLContextFactory sslFactory = new SSLContextFactory(trustStore.getStoreLocation(),
                        trustStore.getPassword(), trustStore.getStoreAlgorithm(), keyStore.getStoreLocation(),
                        keyStore.getPassword(), keyStore.getStoreAlgorithm(), sslProtocols, ciphers);

                for (int sslPort : sslPorts) {
                    NetworkTransportConfiguration settings = new ServerNetworkTransportConfiguration(
                            serverConfig, sslPort, bindAddressFromBrokerOptions, Transport.TCP);

                    IncomingNetworkTransport transport = new MinaNetworkTransport();

                    transport.accept(settings, new AMQProtocolEngineFactory(), sslFactory);

                    ApplicationRegistry.getInstance().addAcceptor(
                            new InetSocketAddress(bindAddressForHostname, sslPort),
                            new QpidAcceptor(transport, "TCP"));
                    CurrentActor.get().message(BrokerMessages.LISTENING("TCP/SSL", sslPort));
                }
            }

            CurrentActor.get().message(BrokerMessages.READY());
        } else {
            log.warn("AMQP Transport is disabled as per configuration.");
        }
    } catch (JMException e) {
        throw new AndesException("Unable to register an MBean", e);
    } catch (UnknownHostException e) {
        throw new AndesException("Unable to get bind address", e);
    }
}

From source file:gov.nist.appvet.servlet.AppVetServlet.java

private AppInfo createAppInfo(String userName, String sessionId, FileItem fileItem, String clientIpAddress,
        HttpServletRequest request) {//  ww  w  . j ava2s.  c o  m
    String appId = generateAppid();
    AppInfo appInfo = new AppInfo(appId, true);
    appInfo.userName = userName;
    appInfo.sessionId = sessionId;
    appInfo.fileItem = fileItem;
    appInfo.fileName = FileUtil.getNormalizedFileName(fileItem.getName());
    InetAddress addr;
    try {
        addr = InetAddress.getByName(request.getRemoteHost());
    } catch (UnknownHostException e) {
        log.error(e.getMessage());
        return null;
    }
    appInfo.clientHost = addr.getCanonicalHostName();

    // Set temporary icon until icon is extracted from app
    final String sourceIconPath = AppVetProperties.APP_IMAGES + "/default.png";
    appInfo.log.debug("Source icon: " + sourceIconPath);
    final String destIconPath = AppVetProperties.APP_IMAGES + "/" + appInfo.appId + ".png";
    FileUtil.copyFile(sourceIconPath, destIconPath);
    return appInfo;
}

From source file:nl.nn.adapterframework.extensions.tibco.GetTibcoQueues.java

private String getResolvedUrl(String url) {
    URI uri = null;//from  w  w w .  ja v a 2s.  c om
    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        log.debug("Caught URISyntaxException while resolving url [" + url + "]: " + e.getMessage());
        return null;
    }
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByName(uri.getHost());
    } catch (UnknownHostException e) {
        log.debug("Caught UnknownHostException while resolving url [" + url + "]: " + e.getMessage());
        return null;
    }
    return inetAddress.getCanonicalHostName();
}