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.googlecode.jsendnsca.MessagePayload.java

/**
 * Set the hostname in the passive check
 *
 * @param useCanonical true to use this machines fully qualified domain name, false
 *                     to use the short hostname
 *//* w ww.j  a v  a 2s .c  om*/
public void setHostname(boolean useCanonical) {
    InetAddress ipAddress;
    try {
        ipAddress = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        throw new UnknownHostRuntimeException(e);
    }
    if (useCanonical) {
        this.hostname = ipAddress.getCanonicalHostName();
    } else {
        this.hostname = ipAddress.getHostName();
    }
}

From source file:jp.primecloud.auto.common.component.DnsStrategy.java

protected String getCanonicalName(String fqdn) {
    try {//from  www . j ava2  s. c o m
        InetAddress address = InetAddress.getByName(fqdn);
        return address.getCanonicalHostName();
    } catch (UnknownHostException e) {
        return null;
    }
}

From source file:com.nridge.connector.ws.con_ws.restlet.RestletApplication.java

/**
 * Returns a Restlet instance used to identify inbound requests for the
 * web service endpoints.//from  w w  w.jav  a 2s. c  o m
 *
 * @return Restlet instance.
 */
@Override
public Restlet createInboundRoot() {
    Restlet restletRoot;
    Logger appLogger = mAppMgr.getLogger(this, "createInboundRoot");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Context restletContext = getContext();
    Router restletRouter = new Router(restletContext);

    String propertyName = "restlet.host_names";
    String hostNames = mAppMgr.getString(propertyName);
    if (StringUtils.isEmpty(hostNames)) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();

            routerAttachEndPoints(restletRouter, "localhost");
            routerAttachEndPoints(restletRouter, inetAddress.getHostName());
            routerAttachEndPoints(restletRouter, inetAddress.getHostAddress());
            routerAttachEndPoints(restletRouter, inetAddress.getCanonicalHostName());
        } catch (UnknownHostException e) {
            appLogger.error(e.getMessage(), e);
            routerAttachEndPoints(restletRouter, "localhost");
        }
    } else {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] hostNameList = mAppMgr.getStringArray(propertyName);
            for (String hostName : hostNameList)
                routerAttachEndPoints(restletRouter, hostName);
        }
    }

    RestletFilter restletFilter = new RestletFilter(mAppMgr, restletContext);
    propertyName = "restlet.allow_addresses";
    String allowAddresses = mAppMgr.getString(propertyName);
    if (StringUtils.isNotEmpty(allowAddresses)) {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] allowAddressList = mAppMgr.getStringArray(propertyName);
            for (String allowAddress : allowAddressList) {
                restletFilter.add(allowAddress);
                appLogger.debug("Filter Allow Address: " + allowAddress);
            }
        } else {
            restletFilter.add(allowAddresses);
            appLogger.debug("Filter Allow Address: " + allowAddresses);
        }
        restletFilter.setNext(restletRouter);
        restletRoot = restletFilter;
    } else
        restletRoot = restletRouter;

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return restletRoot;
}

From source file:org.openadaptor.auxil.connector.soap.WebServiceCXFListeningReadConnector.java

/**
 * Programmatic publishing of an Endpoint.
 *//*from  w ww  .j  a  v  a 2 s .c  o  m*/
public void connect() {
    if (server == null) {
        ServerFactoryBean svrFactory = new ServerFactoryBean();
        svrFactory.setServiceClass(IStringDataProcessor.class);
        QName namespace = new QName(NAMESPACE, serviceName);
        InetAddress localMachine = null;
        try {
            localMachine = java.net.InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            String errMsg = "Unable to determine hostname";
            log.error(errMsg, e);
            throw new ConnectionException(errMsg);
        }
        String hostname = localMachine.getCanonicalHostName();
        String endpointUrl = HTTP_PREFIX + hostname + ":" + port + "/" + serviceName;
        svrFactory.setAddress(endpointUrl);
        svrFactory.setServiceBean(this);
        svrFactory.setServiceName(namespace);
        server = svrFactory.create();
        log.info("Created and started WS Endpoint " + getEndpoint());
    } else {
        server.start();
        log.info("Started WS Endpoint " + getEndpoint());
    }
}

From source file:com.nridge.connector.fs.con_fs.restlet.RestletApplication.java

/**
 * Returns a Restlet instance used to identify inbound requests for the
 * web service endpoints./*  w ww  .  j  a  v  a 2s . c o m*/
 *
 * @return Restlet instance.
 */
@Override
public Restlet createInboundRoot() {
    Restlet restletRoot;
    Logger appLogger = mAppMgr.getLogger(this, "createInboundRoot");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Context restletContext = getContext();
    Router restletRouter = new Router(restletContext);

    String propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.host_names";
    String hostNames = mAppMgr.getString(propertyName);
    if (StringUtils.isEmpty(hostNames)) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();

            routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT);
            routerAttachEndPoints(restletRouter, inetAddress.getHostName());
            routerAttachEndPoints(restletRouter, inetAddress.getHostAddress());
            routerAttachEndPoints(restletRouter, inetAddress.getCanonicalHostName());
        } catch (UnknownHostException e) {
            appLogger.error(e.getMessage(), e);
            routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT);
        }
    } else {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] hostNameList = mAppMgr.getStringArray(propertyName);
            for (String hostName : hostNameList)
                routerAttachEndPoints(restletRouter, hostName);
        } else
            routerAttachEndPoints(restletRouter, hostNames);
    }

    RestletFilter restletFilter = new RestletFilter(mAppMgr, restletContext);
    propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.allow_addresses";
    String allowAddresses = mAppMgr.getString(propertyName);
    if (StringUtils.isNotEmpty(allowAddresses)) {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] allowAddressList = mAppMgr.getStringArray(propertyName);
            for (String allowAddress : allowAddressList) {
                restletFilter.add(allowAddress);
                appLogger.debug("Filter Allow Address: " + allowAddress);
            }
        } else {
            restletFilter.add(allowAddresses);
            appLogger.debug("Filter Allow Address: " + allowAddresses);
        }
        restletFilter.setNext(restletRouter);
        restletRoot = restletFilter;
    } else
        restletRoot = restletRouter;

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return restletRoot;
}

From source file:org.sipfoundry.preflight.FTP.java

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;//from   ww w  . j  av  a2 s  .  co m
    InetAddress ftpServerAddress = null;
    String testFile = new String("00D01EFFFFFE");
    String[] verificationStrings = { "LIP-68XX configuration information", "[VOIP]", "outbound_proxy_server",
            "[PROVISION]", "decrypt_key" };

    if (networkResources.configServer == null) {
        journalService.println("No FTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

    journalService.println("Starting FTP server test.");

    if (IPAddressUtil.isLiteralIPAddress(networkResources.configServer)) {
        try {
            ftpServerAddress = InetAddress.getByName(networkResources.configServer);
        } catch (UnknownHostException e) {
            // Should never get here.
            e.printStackTrace();
        }
        journalService.println("Using FTP server literal address: " + networkResources.configServer);
    } else {
        // Try to retrieve A RECORD for FTP server, checking each DNS server.
        SimpleResolver resolver = null;
        try {
            resolver = new SimpleResolver();
            resolver.setLocalAddress(bindAddress);
            resolver.setTimeout(timeout);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up FTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String("  FTP server address \"" + networkResources.configServer + "\"");
            resolver.setAddress(dnsServer);
            Lookup aLookup = null;
            try {
                aLookup = new Lookup(networkResources.configServer, Type.A);
            } catch (TextParseException e) {
                journalService.println("  is malformed.\n");
                journalService.println(targetMessage);
                return FTP_ADDRESS_MALFORMED;
            }
            aLookup.setResolver(resolver);
            Record[] aRecords = aLookup.run();
            switch (aLookup.getResult()) {
            case Lookup.SUCCESSFUL:
                if (aRecords != null) {
                    InetAddress targetAddress = ((ARecord) aRecords[0]).getAddress();
                    targetMessage += " resolves to: " + targetAddress.getHostAddress();
                    journalService.println(targetMessage);
                    if (ftpServerAddress == null) {
                        ftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same
                        // address.
                        if (!ftpServerAddress.equals(targetAddress)) {
                            journalService.println("  FTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = FTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = FTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

    if ((ftpServerAddress == null) || (results == MULTIPLE_CONFIG_TARGETS)) {
        journalService.println("Cannot recover from previous errors, aborting FTP test.\n");
        return results;
    }

    journalService.println("Beginning FTP get request of test file: " + testFile);

    // Open the FTP connection.
    FTPClient ftp = new FTPClient();
    ftp.setDefaultTimeout(timeout * 1000);
    ftp.addProtocolCommandListener(new PrintCommandListener(journalService));

    try {
        int reply;
        ftp.connect(ftpServerAddress, 21, bindAddress, bindPort);

        // After connection, check reply code to verify.
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP client failure: " + reply + "\n");
            return FTP_CLIENT_FAILURE;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
        journalService.println("FTP client failure: " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    }

    try {
        if (!ftp.login(ftpUser, ftpPassword)) {
            ftp.logout();
            journalService.println("FTP client unable to log in.\n");
            return FTP_GET_FAILED;
        }

        journalService.println("FTP client connected to: " + ftp.getSystemName());

        ftp.enterLocalPassiveMode();

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        ftp.retrieveFile(testFile, output);

        // After receiving, check reply code to verify.
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            journalService.println("FTP get failure: " + reply + "\n");
            return FTP_GET_FAILED;
        }

        ftp.logout();

        String testFileContents = output.toString();
        boolean verified = true;
        for (String verificationString : verificationStrings) {
            if (!testFileContents.contains(verificationString)) {
                verified = false;
            }
        }
        if (verified) {
            journalService.println("File received successfully.");
        } else {
            journalService.println("File received but contents do not verify.");
            System.err.println(testFileContents);
            results = FTP_CONTENTS_FAILED;
        }
    } catch (FTPConnectionClosedException e) {
        journalService.println("FTP server closed connection prematurely.\n");
        return FTP_GET_FAILED;
    } catch (IOException e) {
        journalService.println("FTP client failure. " + e.getMessage() + "\n");
        return FTP_CLIENT_FAILURE;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // Ignore.
            }
        }
    }

    journalService.println("");
    return results;
}

From source file:com.kylinolap.job.flow.JobFlowListener.java

/**
 * @param jobInstance/*from  w  w  w .java2 s  . c  o m*/
 */
protected void notifyUsers(JobInstance jobInstance, JobEngineConfig engineConfig) {
    KylinConfig config = engineConfig.getConfig();
    String cubeName = jobInstance.getRelatedCube();
    CubeInstance cubeInstance = CubeManager.getInstance(config).getCube(cubeName);
    String finalStatus = null;
    String content = JobConstants.NOTIFY_EMAIL_TEMPLATE;
    String logMsg = "";

    switch (jobInstance.getStatus()) {
    case FINISHED:
        finalStatus = "SUCCESS";
        break;
    case ERROR:
        for (JobStep step : jobInstance.getSteps()) {
            if (step.getStatus() == JobStepStatusEnum.ERROR) {
                try {
                    logMsg = JobDAO.getInstance(config).getJobOutput(step).getOutput();
                } catch (IOException e) {
                    log.error(e.getLocalizedMessage(), e);
                }
            }
        }
        finalStatus = "FAILED";
        break;
    case DISCARDED:
        finalStatus = "DISCARDED";
    default:
        break;
    }

    if (null == finalStatus) {
        return;
    }

    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        content = content.replaceAll("\\$\\{job_engine\\}", inetAddress.getCanonicalHostName());
    } catch (UnknownHostException e) {
        log.error(e.getLocalizedMessage(), e);
    }

    content = content.replaceAll("\\$\\{job_name\\}", jobInstance.getName());
    content = content.replaceAll("\\$\\{result\\}", finalStatus);
    content = content.replaceAll("\\$\\{cube_name\\}", cubeName);
    content = content.replaceAll("\\$\\{start_time\\}", new Date(jobInstance.getExecStartTime()).toString());
    content = content.replaceAll("\\$\\{duration\\}", jobInstance.getDuration() / 60 + "mins");
    content = content.replaceAll("\\$\\{mr_waiting\\}", jobInstance.getMrWaiting() / 60 + "mins");
    content = content.replaceAll("\\$\\{last_update_time\\}",
            new Date(jobInstance.getLastModified()).toString());
    content = content.replaceAll("\\$\\{error_log\\}", logMsg);

    MailService mailService = new MailService();
    try {
        List<String> users = new ArrayList<String>();

        if (null != cubeInstance.getDescriptor().getNotifyList()) {
            users.addAll(cubeInstance.getDescriptor().getNotifyList());
        }

        if (null != engineConfig.getAdminDls()) {
            String[] adminDls = engineConfig.getAdminDls().split(",");

            for (String adminDl : adminDls) {
                users.add(adminDl);
            }
        }

        if (users.size() > 0) {
            mailService.sendMail(users, "[Kylin Cube Build Job]-" + cubeName + "-" + finalStatus, content);
        }
    } catch (IOException e) {
        log.error(e.getLocalizedMessage(), e);
    }

}

From source file:jp.primecloud.auto.common.component.DnsStrategy.java

protected String getHostName(String ipAddress) {
    byte[] addr = new byte[4];
    String[] octets = StringUtils.split(ipAddress, ".", 4);
    for (int i = 0; i < 4; i++) {
        addr[i] = (byte) Integer.parseInt(octets[i]);
    }//from   w w  w.ja  v a 2 s .  c o  m

    InetAddress address;
    try {
        address = InetAddress.getByAddress(addr);
        return address.getCanonicalHostName();
    } catch (UnknownHostException e) {
        return null;
    }
}

From source file:org.apache.james.dnsservice.dnsjava.DNSJavaService.java

@PostConstruct
public void init() throws Exception {
    logger.debug("DNSService init...");

    // If no DNS servers were configured, default to local host
    if (dnsServers.isEmpty()) {
        try {//from  w w  w. j  a va  2s  . co  m
            dnsServers.add(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException ue) {
            dnsServers.add("127.0.0.1");
        }
    }

    // Create the extended resolver...
    final String[] serversArray = dnsServers.toArray(new String[dnsServers.size()]);

    if (logger.isInfoEnabled()) {
        for (String aServersArray : serversArray) {
            logger.info("DNS Server is: " + aServersArray);
        }
    }

    try {
        resolver = new ExtendedResolver(serversArray);
    } catch (UnknownHostException uhe) {
        logger.error(
                "DNS service could not be initialized.  The DNS servers specified are not recognized hosts.",
                uhe);
        throw uhe;
    }

    cache = new Cache(DClass.IN);
    cache.setMaxEntries(maxCacheSize);

    if (setAsDNSJavaDefault) {
        Lookup.setDefaultResolver(resolver);
        Lookup.setDefaultCache(cache, DClass.IN);
        Lookup.setDefaultSearchPath(searchPaths);
        logger.info("Registered cache, resolver and search paths as DNSJava defaults");
    }

    // Cache the local hostname and local address. This is needed because
    // the following issues:
    // JAMES-787
    // JAMES-302
    InetAddress addr = getLocalHost();
    localCanonicalHostName = addr.getCanonicalHostName();
    localHostName = addr.getHostName();
    localAddress = addr.getHostAddress();

    logger.debug("DNSService ...init end");
}

From source file:org.graphwalker.Util.java

protected static InetAddress getInternetAddr(final String nic) {
    // Find the real network interface
    NetworkInterface iface = null;
    InetAddress ia = null;
    boolean foundNIC = false;
    try {//  ww w  .  j  av  a2  s .c  o  m
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces
                .hasMoreElements() && foundNIC == false;) {
            iface = ifaces.nextElement();
            Util.logger.debug("Interface: " + iface.getDisplayName());
            for (Enumeration<InetAddress> ips = iface.getInetAddresses(); ips.hasMoreElements()
                    && foundNIC == false;) {
                ia = ips.nextElement();
                Util.logger.debug(ia.getCanonicalHostName() + " " + ia.getHostAddress());
                if (!ia.isLoopbackAddress()) {
                    Util.logger.debug("  Not a loopback address...");
                    if (!ia.getHostAddress().contains(":") && nic.equals(iface.getDisplayName())) {
                        Util.logger.debug("  Host address does not contain ':'");
                        Util.logger.debug("  Interface: " + iface.getName()
                                + " seems to be InternetInterface. I'll take it...");
                        foundNIC = true;
                    }
                }
            }
        }
    } catch (SocketException e) {
        Util.logger.error(e.getMessage());
    } finally {
        if (!foundNIC && nic != null) {
            Util.logger.error("Could not bind to network interface: " + nic);
            throw new RuntimeException("Could not bind to network interface: " + nic);
        } else if (!foundNIC) {
            Util.logger.error("Could not bind to any network interface");
            throw new RuntimeException("Could not bind to any network interface: ");
        }
    }
    return ia;
}