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.apache.synapse.core.axis2.SynapseInitializationModule.java

public void init(ConfigurationContext configurationContext, AxisModule axisModule) throws AxisFault {

    log.info("Initializing Synapse at : " + new Date());
    try {/*  ww w  . j a  va2  s  . com*/
        InetAddress addr = InetAddress.getLocalHost();
        if (addr != null) {
            // Get IP Address
            String ipAddr = addr.getHostAddress();
            if (ipAddr != null) {
                MDC.put("ip", ipAddr);
            }

            // Get hostname
            String hostname = addr.getHostName();
            if (hostname == null) {
                hostname = ipAddr;
            }
            MDC.put("host", hostname);
        }
    } catch (UnknownHostException e) {
        log.warn("Unable to determine hostname or IP address of the server for logging", e);
    }

    // this will deploy the mediators in the mediator extensions folder
    log.info("Loading mediator extensions...");
    configurationContext.getAxisConfiguration().getConfigurator().loadServices();

    // Initializing the SynapseEnvironment and SynapseConfiguration
    log.info("Initializing the Synapse configuration ...");
    synCfg = getConfiguration(configurationContext);

    log.info("Deploying the Synapse service..");
    // Dynamically initialize the Synapse Service and deploy it into Axis2
    AxisConfiguration axisCfg = configurationContext.getAxisConfiguration();
    AxisService synapseService = new AxisService(SynapseConstants.SYNAPSE_SERVICE_NAME);
    AxisOperation mediateOperation = new InOutAxisOperation(SynapseConstants.SYNAPSE_OPERATION_NAME);
    mediateOperation.setMessageReceiver(new SynapseMessageReceiver());
    synapseService.addOperation(mediateOperation);
    List transports = new ArrayList();
    transports.add(Constants.TRANSPORT_HTTP);
    transports.add(Constants.TRANSPORT_HTTPS);
    synapseService.setExposedTransports(transports);
    axisCfg.addService(synapseService);

    log.info("Initializing Sandesha 2...");
    AxisModule sandeshaAxisModule = configurationContext.getAxisConfiguration()
            .getModule(SynapseConstants.SANDESHA2_MODULE_NAME);
    if (sandeshaAxisModule != null) {
        Module sandesha2 = sandeshaAxisModule.getModule();
        sandesha2.init(configurationContext, sandeshaAxisModule);
    }

    // this server name is given by system property SynapseServerName
    // otherwise take host-name
    // if nothing found assume localhost
    String thisServerName = System.getProperty(SynapseConstants.SYNAPSE_SERVER_NAME);
    if (thisServerName == null || thisServerName.equals("")) {
        try {
            InetAddress addr = InetAddress.getLocalHost();
            thisServerName = addr.getHostName();

        } catch (UnknownHostException e) {
            log.warn("Could not get local host name", e);
        }

        if (thisServerName == null || thisServerName.equals("")) {
            thisServerName = "localhost";
        }
    }
    log.info("Synapse server name : " + thisServerName);

    log.info("Deploying Proxy services...");
    Iterator iter = synCfg.getProxyServices().iterator();
    while (iter.hasNext()) {
        ProxyService proxy = (ProxyService) iter.next();

        // start proxy service if either,
        // pinned server name list is empty
        // or pinned server list has this server name
        List pinnedServers = proxy.getPinnedServers();
        if (pinnedServers != null && !pinnedServers.isEmpty()) {
            if (!pinnedServers.contains(thisServerName)) {
                log.info("Server name not in pinned servers list. Not deploying Proxy service : "
                        + proxy.getName());
                continue;
            }
        }

        proxy.buildAxisService(synCfg, axisCfg);
        log.info("Deployed Proxy service : " + proxy.getName());
        if (!proxy.isStartOnLoad()) {
            proxy.stop(synCfg);
        }
    }

    log.info("Synapse initialized successfully...!");
}

From source file:org.apereo.portal.jmx.JavaManagementServerBean.java

/**
 * Generates the JMXServiceURL for the two specified ports.
 * /*ww  w.  j  a v  a2 s .  c  o  m*/
 * @return A JMXServiceURL for this host using the two specified ports.
 * @throws IllegalStateException If localhost cannot be resolved or if the JMXServiceURL is malformed.
 */
protected JMXServiceURL getServiceUrl(final int portOne, int portTwo) {
    final String jmxHost;
    if (this.host == null) {
        final InetAddress inetHost;
        try {
            inetHost = InetAddress.getLocalHost();
        } catch (UnknownHostException uhe) {
            throw new IllegalStateException("Cannot resolve localhost InetAddress.", uhe);
        }

        jmxHost = inetHost.getHostName();
    } else {
        jmxHost = this.host;
    }

    final String jmxUrl = "service:jmx:rmi://" + jmxHost + ":" + portTwo + "/jndi/rmi://" + jmxHost + ":"
            + portOne + "/server";

    final JMXServiceURL jmxServiceUrl;
    try {
        jmxServiceUrl = new JMXServiceURL(jmxUrl);
    } catch (MalformedURLException mue) {
        throw new IllegalStateException("Failed to create JMXServiceURL for url String '" + jmxUrl + "'", mue);
    }

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Generated JMXServiceURL='" + jmxServiceUrl + "' from String " + jmxUrl + "'.");
    }

    return jmxServiceUrl;
}

From source file:com.yodlee.sampleapps.helper.OpenSamlHelper.java

/**
 * This function generates the response.
 *
 * @param subjects//from   w  ww.j  ava2s.co m
 * @return SAMLResponse object
 * @throws SAMLException
 * @throws Exception
 */
public SAMLResponse generateResponse(String[] subjects, String issuer) throws SAMLException {
    // Get Host Information
    InetAddress address = null;
    try {
        address = InetAddress.getLocalHost();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
    String IPAddress = address.getHostAddress();
    String DNSAddress = address.getHostName();

    Collection statements = new ArrayList();

    // Create the SAML subject
    for (int i = 0; i < subjects.length; i++) {
        String subject = subjects[i];
        SAMLNameIdentifier nameIdentifier = new SAMLNameIdentifier(subject, null,
                SAMLNameIdentifier.FORMAT_X509);
        List confirmationMethodList = new ArrayList();
        confirmationMethodList.add(SAMLSubject.CONF_BEARER);

        SAMLSubject samlSubject = new SAMLSubject(nameIdentifier, confirmationMethodList, null, null);

        // Create the SAML Authentication Statement
        SAMLAuthenticationStatement sas = new SAMLAuthenticationStatement
        //(subject,"auth",new Date(),IPAddress,DNSAddress,null);
        (samlSubject, "password", new Date(), IPAddress, DNSAddress, null);

        statements.add(sas);
    }

    // Create the SAML Assertion
    SAMLAssertion assertion = new SAMLAssertion
    //(issuer,new Date(),new Date(),null,null,statements);
    (issuer, null, null, null, null, statements);
    Collection assertions = new ArrayList();
    assertions.add(assertion);

    // Create the SAML Response
    SAMLResponse response = null;
    response = new SAMLResponse("artifact", subjects[0], assertions, null);

    Collection dsa_certs = new ArrayList();
    for (int i = 0; i < OpenSamlHelper.certs.length; i++)
        dsa_certs.add(OpenSamlHelper.certs[i]);

    // Sign the Response
    try {
        response.sign(XMLSignature.ALGO_ID_SIGNATURE_RSA, OpenSamlHelper.privateKey, dsa_certs);
    } catch (SAMLException e) {
        System.out.println("SAMLException.  Error signing the response.");
        e.printStackTrace();
    }
    //response.toStream( System.out);

    return response;
}

From source file:org.miloss.fgsms.common.Utility.java

/**
 * returns the lowercase hostname/* w w w  .jav  a  2 s.  com*/
 *
 * @return
 */
public static String getHostName() {
    if (myHostname == null) {
        try {
            InetAddress addr = InetAddress.getLocalHost();

            // Get IP Address
            // byte[] ipAddr = addr.getAddress();
            // Get hostname
            myHostname = addr.getHostName().toLowerCase();
        } catch (Exception e) {
            myHostname = "ADDRESS_UNKNOWN";
        }
    }
    return myHostname;
}

From source file:com.dianping.wed.cache.redis.biz.WeddingRedisKeyConfigurationServiceImpl.java

@Override
public Map<String, Object> queryMemoryCache(String... categories) {
    Map<String, Object> results = new LinkedHashMap<String, Object>();
    for (String category : categories) {
        results.put(category, keyCfgCache.get(category));
    }//  ww w.  jav  a2s  .  co m
    InetAddress localHost = null;
    try {
        localHost = InetAddress.getLocalHost();
    } catch (Exception e) {
        logger.error("call InetAddress.getLocalHost() error", e);
    }

    if (localHost == null) {
        results.put("HostName", "UNKNOWN");
    } else {
        results.put("HostName", localHost.getHostName());
    }
    return results;
}

From source file:org.openhab.binding.wol.internal.WolBinding.java

private void sendWolPacket(WolBindingConfig config) {

    if (config == null) {
        logger.error("given parameter 'config' must not be null");
        return;/*w  w  w.ja  va  2 s  . co m*/
    }

    InetAddress address = config.address;
    byte[] macBytes = config.macBytes;

    try {

        byte[] bytes = fillMagicBytes(macBytes);

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, PORT);

        DatagramSocket socket = new DatagramSocket();
        socket.send(packet);
        socket.close();

        logger.info("Wake-on-LAN packet sent [broadcastIp={}, macaddress={}]", address.getHostName(),
                String.valueOf(Hex.encodeHex(macBytes)));
    } catch (Exception e) {
        logger.error("Failed to send Wake-on-LAN packet [broadcastIp=" + address.getHostAddress()
                + ", macaddress=" + String.valueOf(Hex.encodeHex(macBytes)) + "]", e);
    }

}

From source file:com.norconex.commons.lang.url.URLNormalizer.java

/**
 * <p>Replaces IP address with domain name.  This is often not
 * reliable due to virtual domain names and can be slow, as it has
 * to access the network.</p>/*from   w ww. j a va  2s.  c om*/
 * <code>http://208.77.188.166/ &rarr; http://www.example.com/</code>
 * @return this instance
 */
public URLNormalizer replaceIPWithDomainName() {
    URI u = toURI(url);
    if (!PATTERN_DOMAIN.matcher(u.getHost()).matches()) {
        try {
            InetAddress addr = InetAddress.getByName(u.getHost());
            String host = addr.getHostName();
            if (!u.getHost().equalsIgnoreCase(host)) {
                url = url.replaceFirst(u.getHost(), host);
            }
        } catch (UnknownHostException e) {
            LOG.debug("Cannot resolve IP to host for :" + u.getHost(), e);
        }
    }
    return this;
}

From source file:com.summit.jbeacon.buoys.MultiCastResourceBuoy.java

private ResourcePacket generateResourcePacket(final Socket socket) throws MultiCastResourceBuoyException {
    ResourcePacket retVal = new ResourcePacket();
    InetAddress guessedAddress = guessHostAddress(socket);
    retVal.setDefaultHostName(guessedAddress.getHostName());
    retVal.setDefaultIp(guessedAddress.getHostAddress());
    for (int i = 0; i < availableResources.size(); i++) {
        Resource r = availableResources.get(i);
        retVal.getResources().add(r);/*from www  . j  a v  a 2s.c  o  m*/
    }
    return retVal;
}

From source file:org.apache.hadoop.mapreduce.JobSubmitter.java

/**
 * Internal method for submitting jobs to the system.
 * /*  w ww  .j  ava2  s  . c  om*/
 * <p>The job submission process involves:
 * <ol>
 *   <li>
 *   Checking the input and output specifications of the job.
 *   </li>
 *   <li>
 *   Computing the {@link InputSplit}s for the job.
 *   </li>
 *   <li>
 *   Setup the requisite accounting information for the 
 *   {@link DistributedCache} of the job, if necessary.
 *   </li>
 *   <li>
 *   Copying the job's jar and configuration to the map-reduce system
 *   directory on the distributed file-system. 
 *   </li>
 *   <li>
 *   Submitting the job to the <code>JobTracker</code> and optionally
 *   monitoring it's status.
 *   </li>
 * </ol></p>
 * @param job the configuration to submit
 * @param cluster the handle to the Cluster
 * @throws ClassNotFoundException
 * @throws InterruptedException
 * @throws IOException
 */
JobStatus submitJobInternal(Job job, Cluster cluster)
        throws ClassNotFoundException, InterruptedException, IOException {

    //validate the jobs output specs 
    checkSpecs(job);

    Configuration conf = job.getConfiguration();
    addMRFrameworkToDistributedCache(conf);

    Path jobStagingArea = JobSubmissionFiles.getStagingDir(cluster, conf);
    //configure the command line options correctly on the submitting dfs
    InetAddress ip = InetAddress.getLocalHost();
    if (ip != null) {
        submitHostAddress = ip.getHostAddress();
        submitHostName = ip.getHostName();
        conf.set(MRJobConfig.JOB_SUBMITHOST, submitHostName);
        conf.set(MRJobConfig.JOB_SUBMITHOSTADDR, submitHostAddress);
    }
    JobID jobId = submitClient.getNewJobID();
    job.setJobID(jobId);
    Path submitJobDir = new Path(jobStagingArea, jobId.toString());
    JobStatus status = null;
    try {
        conf.set(MRJobConfig.USER_NAME, UserGroupInformation.getCurrentUser().getShortUserName());
        conf.set("hadoop.http.filter.initializers",
                "org.apache.hadoop.yarn.server.webproxy.amfilter.AmFilterInitializer");
        conf.set(MRJobConfig.MAPREDUCE_JOB_DIR, submitJobDir.toString());
        LOG.debug("Configuring job " + jobId + " with " + submitJobDir + " as the submit dir");
        // get delegation token for the dir
        TokenCache.obtainTokensForNamenodes(job.getCredentials(), new Path[] { submitJobDir }, conf);

        populateTokenCache(conf, job.getCredentials());

        // generate a secret to authenticate shuffle transfers
        if (TokenCache.getShuffleSecretKey(job.getCredentials()) == null) {
            KeyGenerator keyGen;
            try {
                keyGen = KeyGenerator.getInstance(SHUFFLE_KEYGEN_ALGORITHM);
                keyGen.init(SHUFFLE_KEY_LENGTH);
            } catch (NoSuchAlgorithmException e) {
                throw new IOException("Error generating shuffle secret key", e);
            }
            SecretKey shuffleKey = keyGen.generateKey();
            TokenCache.setShuffleSecretKey(shuffleKey.getEncoded(), job.getCredentials());
        }
        if (CryptoUtils.isEncryptedSpillEnabled(conf)) {
            conf.setInt(MRJobConfig.MR_AM_MAX_ATTEMPTS, 1);
            LOG.warn("Max job attempts set to 1 since encrypted intermediate" + "data spill is enabled");
        }

        copyAndConfigureFiles(job, submitJobDir);

        Path submitJobFile = JobSubmissionFiles.getJobConfPath(submitJobDir);

        // Create the splits for the job
        LOG.debug("Creating splits at " + jtFs.makeQualified(submitJobDir));
        int maps = writeSplits(job, submitJobDir);
        conf.setInt(MRJobConfig.NUM_MAPS, maps);
        LOG.info("number of splits:" + maps);

        // write "queue admins of the queue to which job is being submitted"
        // to job file.
        String queue = conf.get(MRJobConfig.QUEUE_NAME, JobConf.DEFAULT_QUEUE_NAME);
        AccessControlList acl = submitClient.getQueueAdmins(queue);
        conf.set(toFullPropertyName(queue, QueueACL.ADMINISTER_JOBS.getAclName()), acl.getAclString());

        // removing jobtoken referrals before copying the jobconf to HDFS
        // as the tasks don't need this setting, actually they may break
        // because of it if present as the referral will point to a
        // different job.
        TokenCache.cleanUpTokenReferral(conf);

        if (conf.getBoolean(MRJobConfig.JOB_TOKEN_TRACKING_IDS_ENABLED,
                MRJobConfig.DEFAULT_JOB_TOKEN_TRACKING_IDS_ENABLED)) {
            // Add HDFS tracking ids
            ArrayList<String> trackingIds = new ArrayList<String>();
            for (Token<? extends TokenIdentifier> t : job.getCredentials().getAllTokens()) {
                trackingIds.add(t.decodeIdentifier().getTrackingId());
            }
            conf.setStrings(MRJobConfig.JOB_TOKEN_TRACKING_IDS,
                    trackingIds.toArray(new String[trackingIds.size()]));
        }

        // Set reservation info if it exists
        ReservationId reservationId = job.getReservationId();
        if (reservationId != null) {
            conf.set(MRJobConfig.RESERVATION_ID, reservationId.toString());
        }

        // Write job file to submit dir
        writeConf(conf, submitJobFile);

        //
        // Now, actually submit the job (using the submit name)
        //
        printTokens(jobId, job.getCredentials());
        status = submitClient.submitJob(jobId, submitJobDir.toString(), job.getCredentials());
        if (status != null) {
            return status;
        } else {
            throw new IOException("Could not launch job");
        }
    } finally {
        if (status == null) {
            LOG.info("Cleaning up the staging area " + submitJobDir);
            if (jtFs != null && submitJobDir != null)
                jtFs.delete(submitJobDir, true);

        }
    }
}

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 {/* w  w  w . j  av  a2s.  c o  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");
}