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:org.apache.hadoop.util.MachineList.java

/**
 * Accepts an ip address and return true if ipAddress is in the list
 * @param ipAddress//  w  ww. j a  v  a  2 s  . co m
 * @return true if ipAddress is part of the list
 */
public boolean includes(String ipAddress) {

    if (all) {
        return true;
    }

    if (ipAddress == null) {
        throw new IllegalArgumentException("ipAddress is null.");
    }

    //check in the set of ipAddresses
    if ((ipAddresses != null) && ipAddresses.contains(ipAddress)) {
        return true;
    }

    //iterate through the ip ranges for inclusion
    if (cidrAddresses != null) {
        for (SubnetUtils.SubnetInfo cidrAddress : cidrAddresses) {
            if (cidrAddress.isInRange(ipAddress)) {
                return true;
            }
        }
    }

    //check if the ipAddress matches one of hostnames
    if (hostNames != null) {
        //convert given ipAddress to hostname and look for a match
        InetAddress hostAddr;
        try {
            hostAddr = addressFactory.getByName(ipAddress);
            if ((hostAddr != null) && hostNames.contains(hostAddr.getCanonicalHostName())) {
                return true;
            }
        } catch (UnknownHostException e) {
            //ignore the exception and proceed to resolve the list of hosts
        }

        //loop through host addresses and convert them to ip and look for a match
        for (String host : hostNames) {
            try {
                hostAddr = addressFactory.getByName(host);
            } catch (UnknownHostException e) {
                continue;
            }
            if (hostAddr.getHostAddress().equals(ipAddress)) {
                return true;
            }
        }
    }
    return false;
}

From source file:info.pancancer.arch3.reporting.Arch3ReportImpl.java

@Override
public Map<String, String> getEnvironmentMap() {
    Map<String, String> env = new TreeMap<>();
    env.put("version", this.getClass().getPackage().getImplementationVersion());
    try {//from   w  ww .  j  a  v a2s. c  o m
        Constants constantsInstance = new Constants();
        Class constants = Class.forName("info.pancancer.arch3.utils.Constants");
        Field[] declaredFields = constants.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().contains("PASSWORD")) {
                continue;
            }
            String settingKey = field.get(constantsInstance).toString();
            if (this.settings.containsKey(settingKey)) {
                env.put(settingKey, this.settings.getString(settingKey));
            }
        }
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(ex);
    } catch (IllegalArgumentException | IllegalAccessException ex) {
        throw new RuntimeException(ex);
    }

    try {
        // stolen from stack overflow
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        String ip;
        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(whatismyip.openStream(), StandardCharsets.UTF_8))) {
            ip = in.readLine(); // you get the IP as a String
        }
        // reverse ip address
        InetAddress addr = InetAddress.getByName(ip);
        env.put("canonical_host_name", addr.getCanonicalHostName());
        env.put("host_name", addr.getHostName());
    } catch (IOException e) {
        System.out.println("Could not lookup ip address of self");
    }

    return env;
}

From source file:org.apache.kylin.engine.mr.CubingJob.java

/**
 * build fail because the metadata store has problem.
 * @param exception/*  w w  w  . j  a va 2  s  .  co m*/
 */
@Override
protected void handleMetaDataPersistException(Exception exception) {
    String title = "[ERROR] - [" + getDeployEnvName() + "] - [" + getProjectName() + "] - "
            + CubingExecutableUtil.getCubeName(this.getParams());
    String content = ExecutableConstants.NOTIFY_EMAIL_TEMPLATE;
    final String UNKNOWN = "UNKNOWN";
    String errMsg = null;
    if (exception != null) {
        final StringWriter out = new StringWriter();
        exception.printStackTrace(new PrintWriter(out));
        errMsg = out.toString();
    }

    content = content.replaceAll("\\$\\{job_name\\}", getName());
    content = content.replaceAll("\\$\\{result\\}", ExecutableState.ERROR.toString());
    content = content.replaceAll("\\$\\{env_name\\}", getDeployEnvName());
    content = content.replaceAll("\\$\\{project_name\\}", getProjectName());
    content = content.replaceAll("\\$\\{cube_name\\}", CubingExecutableUtil.getCubeName(this.getParams()));
    content = content.replaceAll("\\$\\{source_records_count\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{start_time\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{duration\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{mr_waiting\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{last_update_time\\}", UNKNOWN);
    content = content.replaceAll("\\$\\{submitter\\}", StringUtil.noBlank(getSubmitter(), "missing submitter"));
    content = content.replaceAll("\\$\\{error_log\\}",
            Matcher.quoteReplacement(StringUtil.noBlank(errMsg, "no error message")));

    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        content = content.replaceAll("\\$\\{job_engine\\}", inetAddress.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.warn(e.getLocalizedMessage(), e);
    }
    sendMail(Pair.of(title, content));
}

From source file:org.trafodion.rest.util.NetworkConfiguration.java

public InetAddress getInetAddress(NetworkInterface ni) throws Exception {
    InetAddress inet = null;
    Enumeration<InetAddress> rawAdrs = ni.getInetAddresses();
    while (rawAdrs.hasMoreElements()) {
        inet = rawAdrs.nextElement();//from   ww  w .  j  a  v  a2  s  .co m
        LOG.info("Match Found interface [" + ni.toString() + "," + ni.getDisplayName() + ","
                + inet.getCanonicalHostName() + "," + inet.getHostAddress() + "]");
    }
    matchedInterface = true;
    return inet;
}

From source file:com.buaa.cfs.nfs3.NfsExports.java

public AccessPrivilege getAccessPrivilege(InetAddress addr) {
    return getAccessPrivilege(addr.getHostAddress(), addr.getCanonicalHostName());
}

From source file:org.apache.kylin.engine.mr.CubingJob.java

@Override
protected Pair<String, String> formatNotifications(ExecutableContext context, ExecutableState state) {
    CubeInstance cubeInstance = CubeManager.getInstance(context.getConfig())
            .getCube(CubingExecutableUtil.getCubeName(this.getParams()));
    final Output output = getManager().getOutput(getId());
    String logMsg;/*from  w w w  .  j av  a  2s. c  o  m*/
    state = output.getState();
    if (state != ExecutableState.ERROR
            && !cubeInstance.getDescriptor().getStatusNeedNotify().contains(state.toString())) {
        logger.info("state:" + state + " no need to notify users");
        return null;
    }
    switch (state) {
    case ERROR:
        logMsg = output.getVerboseMsg();
        break;
    case DISCARDED:
        logMsg = "job has been discarded";
        break;
    case SUCCEED:
        logMsg = "job has succeeded";
        break;
    default:
        return null;
    }
    String content = ExecutableConstants.NOTIFY_EMAIL_TEMPLATE;
    content = content.replaceAll("\\$\\{job_name\\}", getName());
    content = content.replaceAll("\\$\\{result\\}", state.toString());
    content = content.replaceAll("\\$\\{env_name\\}", getDeployEnvName());
    content = content.replaceAll("\\$\\{project_name\\}", getProjectName());
    content = content.replaceAll("\\$\\{cube_name\\}", CubingExecutableUtil.getCubeName(this.getParams()));
    content = content.replaceAll("\\$\\{source_records_count\\}", String.valueOf(findSourceRecordCount()));
    content = content.replaceAll("\\$\\{start_time\\}", new Date(getStartTime()).toString());
    content = content.replaceAll("\\$\\{duration\\}", getDuration() / 60000 + "mins");
    content = content.replaceAll("\\$\\{mr_waiting\\}", getMapReduceWaitTime() / 60000 + "mins");
    content = content.replaceAll("\\$\\{last_update_time\\}", new Date(getLastModified()).toString());
    content = content.replaceAll("\\$\\{submitter\\}", StringUtil.noBlank(getSubmitter(), "missing submitter"));
    content = content.replaceAll("\\$\\{error_log\\}",
            Matcher.quoteReplacement(StringUtil.noBlank(logMsg, "no error message")));

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

    String title = "[" + state.toString() + "] - [" + getDeployEnvName() + "] - [" + getProjectName() + "] - "
            + CubingExecutableUtil.getCubeName(this.getParams());

    return Pair.of(title, content);
}

From source file:org.addsimplicity.anicetus.TelemetryContext.java

private void sniffHost() {
    if (m_reportingNode == null) {
        try {/* w w w .  j  av  a  2  s.c  o m*/
            final InetAddress local = InetAddress.getLocalHost();
            m_reportingNode = local.getCanonicalHostName();
        } catch (final UnknownHostException e) {
            // Not sure what else to do. Just local host it.
            //
            m_reportingNode = "127.0.0.1";
        }
    }
}

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

public ResultCode validate(int timeout, NetworkResources networkResources, JournalService journalService,
        InetAddress bindAddress) {
    ResultCode results = NONE;//  w w w .  ja va  2  s.c  o m
    InetAddress tftpServerAddress = 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 TFTP server provided, skipping test.\n");
        return CONFIG_SERVER_MISSING;
    }

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

    TFTPClient tftp = new TFTPClient();

    tftp.setDefaultTimeout(timeout * 1000);

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

        for (InetAddress dnsServer : networkResources.domainNameServers) {
            journalService.println(
                    "Looking up TFTP server address via DNS server: " + dnsServer.getCanonicalHostName());
            String targetMessage = new String(
                    "  TFTP 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 TFTP_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 (tftpServerAddress == null) {
                        tftpServerAddress = targetAddress;
                    } else {
                        // Check that multiple lookups result in same address.
                        if (!tftpServerAddress.equals(targetAddress)) {
                            journalService.println("  TFTP server address does not match prior lookup.");
                            results = MULTIPLE_CONFIG_TARGETS;
                        }
                    }
                } else {
                    targetMessage += " could not be resolved.";
                    journalService.println(targetMessage);
                    results = TFTP_TARGET_UNRESOLVED;
                }
                break;
            case Lookup.UNRECOVERABLE:
                targetMessage += " [Unrecoverable error]";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TRY_AGAIN:
                targetMessage += " [Lookup timeout]";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.HOST_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            case Lookup.TYPE_NOT_FOUND:
                targetMessage += " could not be resolved.";
                journalService.println(targetMessage);
                results = TFTP_TARGET_UNRESOLVED;
                break;
            }
        }
    }

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

    journalService.println("Beginning TFTP get request of test file: " + testFile);
    // Open local socket
    try {
        tftp.open();
    } catch (SocketException e) {
        journalService.println("TFTP client failure. " + e.getMessage() + "\n");
        return TFTP_CLIENT_FAILURE;
    }

    // Try to receive remote file via TFTP
    try {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tftp.open(bindPort, bindAddress);
        tftp.receiveFile(testFile, org.apache.commons.net.tftp.TFTP.ASCII_MODE, output, tftpServerAddress);
        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.");
            results = TFTP_CONTENTS_FAILED;
        }
    } catch (UnknownHostException e) {
        journalService.println("TFTP client failure. " + e.getMessage());
        results = TFTP_CLIENT_FAILURE;
    } catch (IOException e) {
        journalService.println("TFTP get failed. " + e.getMessage());
        results = TFTP_GET_FAILED;
    } finally {
        // Close local socket and output file
        tftp.close();
    }

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

From source file:org.apache.hadoop.test.system.process.HadoopDaemonRemoteCluster.java

protected void populateDaemon(HadoopDaemonInfo info) throws IOException {
    for (String host : info.hostNames) {
        InetAddress addr = InetAddress.getByName(host);
        RemoteProcess process = getProcessManager(info, addr.getCanonicalHostName());
        processes.add(process);//w w w  .  ja va 2s  .  co  m
    }
}

From source file:org.rhq.plugins.netservices.PingNetServiceComponent.java

public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) throws Exception {
    String addressString = resourceContext.getPluginConfiguration().getSimple(CONFIG_ADDRESS).getStringValue();
    InetAddress address = InetAddress.getByName(addressString);

    for (MeasurementScheduleRequest request : metrics) {
        if (request.getName().equals("ipAddress")) {
            report.addData(new MeasurementDataTrait(request, address.getHostAddress()));
        } else if (request.getName().equals("hostName")) {
            report.addData(new MeasurementDataTrait(request, address.getCanonicalHostName()));
        } else if (request.getName().equals("responseTime")) {
            long start = System.currentTimeMillis();
            address.isReachable(5000);/*from  w  ww  . j a  va  2  s  .c om*/
            report.addData(new MeasurementDataNumeric(request, (double) (System.currentTimeMillis() - start)));
        }
    }
}