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:org.ejbca.ui.web.admin.configuration.EjbcaWebBean.java

/**
 * @return The host's name or "unknown" if it could not be determined.
 *///from  w w w.  ja va2  s.  com
public String getHostName() {
    String hostname = "unknown";
    try {
        InetAddress addr = InetAddress.getLocalHost();
        // Get hostname
        hostname = addr.getHostName();
    } catch (UnknownHostException e) {
        // Ignored
    }
    return hostname;
}

From source file:xc.mst.harvester.HarvestManager.java

/**
 * Builds and sends an email report about the harvest to the schedule's notify email address.
 *
 * @param problem//from www.j  a v a2s.c  om
 *            The problem which prevented the harvest from finishing, or null if the harvest was successful
 */
protected boolean sendReportEmail(String problem) {
    if (harvestSchedule.getNotifyEmail() != null && mailer.isConfigured()) {
        // The email's subject
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            log.error("Host name query failed.", e);
        }
        String subject = "Results of harvesting " + harvestSchedule.getProvider().getOaiProviderUrl()
                + " by MST Server on " + addr.getHostName();

        // The email's body
        StringBuilder body = new StringBuilder();

        // First report any problems which prevented the harvest from finishing
        if (problem != null)
            body.append("The harvest failed for the following reason: ").append(problem).append("\n\n");

        /*
        if(this.records2ProcessThisRun!=0) {
        body.append("Total number of records available for harvest =").append(totalRecords).append(" \n");
        body.append("Number of records harvested =").append(recordsProcessed).append(" \n");
        }
        */

        return mailer.sendEmail(harvestSchedule.getNotifyEmail(), subject, body.toString());
    } else {
        // note, after configuring email, seem to have to restart MST for it to work.
        log.debug("HarvestManager.sendReportEmail-mail is not configured right! sendto:"
                + harvestSchedule.getNotifyEmail() + " isConfigured:" + mailer.isConfigured());
        return false;
    }
}

From source file:org.infoglue.cms.util.CmsPropertyHandler.java

/**
 * This method initializes the parameter hash with values.
 *///from   w w  w .j a  va  2 s .c om

public static void initializeProperties() {
    try {
        Timer timer = new Timer();
        timer.setActive(false);

        System.out.println("Initializing properties from file.....");
        //Thread.dumpStack();

        cachedProperties = new Properties();
        if (propertyFile != null)
            cachedProperties.load(new FileInputStream(propertyFile));
        else
            cachedProperties.load(CmsPropertyHandler.class.getClassLoader()
                    .getResource("/" + applicationName + ".properties").openStream());
        //cachedProperties.load(CmsPropertyHandler.class.getResourceAsStream("/" + applicationName + ".properties"));

        if (logger.isInfoEnabled())
            cachedProperties.list(System.out);

        Enumeration enumeration = cachedProperties.keys();
        while (enumeration.hasMoreElements()) {
            String key = (String) enumeration.nextElement();
            if (key.indexOf("webwork.") > 0) {
                webwork.config.Configuration.set(key, cachedProperties.getProperty(key));
            }
        }

        timer.printElapsedTime("Initializing properties from file took");

        Map args = new HashMap();
        args.put("globalKey", "infoglue");
        try {
            propertySet = PropertySetManager.getInstance("jdbc", args);
            //logger.info("propertySet:" + propertySet);
            //logger.info("propertySet.allowedAdminIP:" + propertySet.getString("allowedAdminIP"));
            if (logger.isInfoEnabled())
                logger.info("propertySet: " + propertySet);
        } catch (Exception e) {
            propertySet = null;
            logger.error("Could not get property set: " + e.getMessage(), e);
        }

        timer.printElapsedTime("Initializing properties from jdbc");

        serverNodeName = cachedProperties.getProperty("serverNodeName");

        if (serverNodeName == null || serverNodeName.length() == 0) {
            try {
                InetAddress localhost = InetAddress.getLocalHost();
                serverNodeName = localhost.getHostName();
            } catch (Exception e) {
                logger.error("Error initializing serverNodeName:" + e.getMessage());
            }
        }

        logger.info("serverNodeName:" + serverNodeName);

        initializeLocalServerNodeId();

        timer.printElapsedTime("Initializing properties from local server jdbc");
    } catch (Exception e) {
        cachedProperties = null;
        logger.error("Error loading properties from file " + "/" + applicationName + ".properties" + ". Reason:"
                + e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.gatein.management.portalobjects.client.impl.RestfulPortalObjectsMgmtClient.java

public RestfulPortalObjectsMgmtClient(InetAddress address, int port, String username, String password,
        String containerName, BindingProvider bindingProvider) {
    ResteasyProviderFactory instance = ResteasyProviderFactory.getInstance();
    instance.registerProviderInstance(new BindingRestProvider(bindingProvider));
    RegisterBuiltin.register(instance);//w ww.j  a v  a 2 s .c o m

    StringBuilder hostUri = new StringBuilder();
    //TODO: Document this...
    String sslAuth = System.getProperty("org.gatein.management.ssl.client.auth");
    boolean ssl = "true".equals(sslAuth);

    if (ssl) {
        hostUri.append("https");
    } else {
        hostUri.append("http");
    }
    hostUri.append("://").append(address.getHostName());

    if ((ssl && port != 443) || (!ssl && port != 80)) {
        hostUri.append(':').append(port);
    }

    String host = hostUri.toString();
    String restContext = getRestContext(host, containerName);

    Credentials credentials = new UsernamePasswordCredentials(username, password);
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY, credentials);
    httpClient.getParams().setAuthenticationPreemptive(true);
    try {
        StringBuilder uri = new StringBuilder().append(host).append("/").append(restContext).append("/private")
                .append(PORTAL_OBJECTS_URI);

        ClientRequestFactory clientRequestFactory = new ClientRequestFactory(
                new ApacheHttpClientExecutor(httpClient), new URI(uri.toString()));

        siteClientStub = clientRequestFactory.createProxy(SiteClientStub.class);
        pageClientStub = clientRequestFactory.createProxy(PageClientStub.class);
        navigationClientStub = clientRequestFactory.createProxy(NavigationClientStub.class);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Could not create restful client.", e);
    }
}

From source file:org.onebusaway.siri.core.SiriCommon.java

/**
 * If the user has specified a wildcard "*" in their {@link #getUrl()},
 * indicating that they want to bind to all interfaces on their machine, we
 * still need a hostname for when we broadcast that URL to SIRI endpoints for
 * pub-sub callbacks. This method constructs a URL with the "*" replaced with
 * the machine's hostname./*w  w  w  .j a va 2s  . c  o  m*/
 * 
 * @param url
 * @return
 */
protected String replaceHostnameWildcardWithPublicHostnameInUrl(String url) {

    try {
        URL asURL = new URL(url);
        if (asURL.getHost().equals("*")) {
            InetAddress address = Inet4Address.getLocalHost();
            String hostname = address.getHostName();
            return url.replace("*", hostname);
        }
    } catch (UnknownHostException e) {

    } catch (MalformedURLException e) {

    }

    return url;
}

From source file:com.pidoco.juri.JURI.java

/**
 * Does not attempt name resolution (and therefore does not block).
 *
 * @param address to set as hostname. Works with both ipv4 and ipv6 addresses. ipv4 addresses in ipv6 form are
 *                set as ipv6 address. A given ipv4 address is not converted into an ipv6 address.
 * @param useHostIfAvailable if true, checks if the address has a known hostname
 *                           and uses that name instead of the address. Consider using {@link #setHost(String)}}
 *                           directly instead.
 *                           No name resolution is performed at the penalty of additional string concatenation
 *                           when using {@link InetAddress#toString()}.
 *///from w  w  w . j  a v  a  2 s .co m
public JURI setHost(@Nullable InetAddress address, boolean useHostIfAvailable) {
    if (address == null) {
        return setHost("");
    }

    if (useHostIfAvailable && checkIfAddressHasHostnameWithoutNameLookup(address)) {
        this.setHost(address.getHostName());
    } else {
        this.setHost(InetAddresses.toUriString(address));
    }
    return this;
}

From source file:hudson.plugins.dimensionsscm.DimensionsSCM.java

@Override
public boolean checkout(final AbstractBuild build, final Launcher launcher, final FilePath workspace,
        final BuildListener listener, final File changelogFile) throws IOException, InterruptedException {
    boolean bRet = false;

    if (!isCanJobUpdate()) {
        Logger.Debug("Skipping checkout - " + this.getClass().getName());
    }/*from   www  .  j  a  v  a2 s.c  o m*/

    Logger.Debug("Invoking checkout - " + this.getClass().getName());

    try {
        // Load other Dimensions plugins if set
        DimensionsBuildWrapper.DescriptorImpl bwplugin = (DimensionsBuildWrapper.DescriptorImpl) Hudson
                .getInstance().getDescriptor(DimensionsBuildWrapper.class);
        DimensionsBuildNotifier.DescriptorImpl bnplugin = (DimensionsBuildNotifier.DescriptorImpl) Hudson
                .getInstance().getDescriptor(DimensionsBuildNotifier.class);

        if (DimensionsChecker.isValidPluginCombination(build, listener)) {
            Logger.Debug("Plugins are ok");
        } else {
            listener.fatalError("\n[DIMENSIONS] The plugin combinations you have selected are not valid.");
            listener.fatalError("\n[DIMENSIONS] Please review online help to determine valid plugin uses.");
            return false;
        }

        if (isCanJobUpdate()) {
            int version = 2009;
            long key = dmSCM.login(getJobUserName(), getJobPasswd(), getJobDatabase(), getJobServer());

            if (key > 0) {
                // Get the server version
                Logger.Debug("Login worked.");
                version = dmSCM.getDmVersion();
                if (version == 0) {
                    version = 2009;
                }
                dmSCM.logout(key);
            }

            // Get the details of the master
            InetAddress netAddr = InetAddress.getLocalHost();
            byte[] ipAddr = netAddr.getAddress();
            String hostname = netAddr.getHostName();

            boolean master = false;
            GetHostDetailsTask buildHost = new GetHostDetailsTask(hostname);
            master = workspace.act(buildHost);

            if (master) {
                // Running on master...
                listener.getLogger().println("[DIMENSIONS] Running checkout on master...");
                listener.getLogger().flush();

                // Using Java API because this allows the plugin to work on platforms
                // where Dimensions has not been ported, e.g. MAC OS, which is what
                // I use
                CheckOutAPITask task = new CheckOutAPITask(build, this, workspace, listener, version);
                bRet = workspace.act(task);
            } else {
                // Running on slave... Have to use the command line as Java API will not
                // work on remote hosts. Cannot serialise it...

                {
                    // VariableResolver does not appear to be serialisable either, so...
                    VariableResolver<String> myResolver = build.getBuildVariableResolver();

                    String baseline = myResolver.resolve("DM_BASELINE");
                    String requests = myResolver.resolve("DM_REQUEST");

                    listener.getLogger().println("[DIMENSIONS] Running checkout on slave...");
                    listener.getLogger().flush();

                    CheckOutCmdTask task = new CheckOutCmdTask(getJobUserName(), getJobPasswd(),
                            getJobDatabase(), getJobServer(), getProject(), baseline, requests,
                            isCanJobDelete(), isCanJobRevert(), isCanJobForce(), isCanJobExpand(),
                            isCanJobNoMetadata(), (build.getPreviousBuild() == null), getFolders(), version,
                            permissions, workspace, listener);
                    bRet = workspace.act(task);
                }
            }
        } else {
            bRet = true;
        }

        if (bRet) {
            bRet = generateChangeSet(build, listener, changelogFile);
        }
    } catch (Exception e) {
        String errMsg = e.getMessage();
        if (errMsg == null) {
            errMsg = "An unknown error occurred. Please try the operation again.";
        }
        listener.fatalError("Unable to run checkout callout - " + errMsg);
        // e.printStackTrace();
        //throw new IOException("Unable to run checkout callout - " + e.getMessage());
        bRet = false;
    }
    return bRet;
}

From source file:org.apache.nifi.bootstrap.RunNiFi.java

private String getHostname() {
    String hostname = "Unknown Host";
    String ip = "Unknown IP Address";
    try {/*from   www  .j a v  a  2  s  . c  om*/
        final InetAddress localhost = InetAddress.getLocalHost();
        hostname = localhost.getHostName();
        ip = localhost.getHostAddress();
    } catch (final Exception e) {
        defaultLogger.warn("Failed to obtain hostname for notification due to:", e);
    }

    return hostname + " (" + ip + ")";
}

From source file:org.apache.catalina.valves.ExtendedAccessLogValve.java

/**
 * Prepare for the beginning of active use of the public methods of this
 * component.  This method should be called after <code>configure()</code>,
 * and before any of the public methods of the component are utilized.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 *//*from   ww  w  .ja  v a2 s.c om*/
public void start() throws LifecycleException {

    // Validate and update our current component state
    if (started)
        throw new LifecycleException(sm.getString("extendedAccessLogValve.alreadyStarted"));
    lifecycle.fireLifecycleEvent(START_EVENT, null);
    started = true;

    // Initialize the timeZone, Date formatters, and currentDate
    TimeZone tz = TimeZone.getTimeZone("GMT");
    dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
    dateFormatter.setTimeZone(tz);
    timeFormatter = new SimpleDateFormat("HH:mm:ss");
    timeFormatter.setTimeZone(tz);
    currentDate = new Date(System.currentTimeMillis());
    if (fileDateFormat == null || fileDateFormat.length() == 0)
        fileDateFormat = "yyyy-MM-dd";
    fileDateFormatter = new SimpleDateFormat(fileDateFormat);
    dateStamp = fileDateFormatter.format(currentDate);
    timeTakenFormatter = new DecimalFormat("0.000");

    /* Everybody say ick ... ick */
    try {
        InetAddress inetAddress = InetAddress.getLocalHost();
        myIpAddress = inetAddress.getHostAddress();
        myDNSName = inetAddress.getHostName();
    } catch (Throwable e) {
        myIpAddress = "127.0.0.1";
        myDNSName = "localhost";
    }

    open();

}

From source file:com.alibaba.wasp.master.FServerManager.java

/**
 * Let the server manager know a new fserver has come online
 *
 * @param ia/*from w  ww .  j a va2  s  .c o  m*/
 *          The remote address
 * @param port
 *          The remote port
 * @param serverStartcode
 * @param serverCurrentTime
 *          The current time of the fserver in ms
 * @return The ServerName we know this server as.
 * @throws java.io.IOException
 */
ServerName fserverStartup(final InetAddress ia, final int port, final long serverStartcode,
        long serverCurrentTime) throws IOException {
    // Test for case where we get a entityGroup startup message from a fserver
    // that has been quickly restarted but whose znode expiration handler has
    // not yet run, or from a server whose fail we are currently processing.
    // Test its host+port combo is present in serverAddresstoServerInfo. If it
    // is, reject the server and trigger its expiration. The next time it comes
    // in, it should have been removed from serverAddressToServerInfo and queued
    // for processing by ProcessServerShutdown.
    ServerName sn = new ServerName(ia.getHostName(), port, serverStartcode);
    checkClockSkew(sn, serverCurrentTime);
    checkIsDead(sn, "STARTUP");
    checkAlreadySameHostPort(sn);
    recordNewServer(sn, ServerLoad.EMPTY_SERVERLOAD);
    return sn;
}