Example usage for java.net InetAddress getLocalHost

List of usage examples for java.net InetAddress getLocalHost

Introduction

In this page you can find the example usage for java.net InetAddress getLocalHost.

Prototype

public static InetAddress getLocalHost() throws UnknownHostException 

Source Link

Document

Returns the address of the local host.

Usage

From source file:com.alliander.osgp.acceptancetests.devicemanagement.FindDevicesSteps.java

@DomainStep("a device (.*) with ownerid (.*) and ownername (.*)")
public void andADevice(final String deviceIdentification, final String ownerId, final String ownerName)
        throws UnknownHostException {
    this.ownerOrganisation = new Organisation(ownerId, ownerName, ORGANISATION_PREFIX,
            PlatformFunctionGroup.ADMIN);

    this.device = new DeviceBuilder().withDeviceIdentification(deviceIdentification)
            .withNetworkAddress(InetAddress.getLocalHost()).build();

    this.device.addAuthorization(this.ownerOrganisation, DeviceFunctionGroup.OWNER);

    this.pageRequest = new PageRequest(DEFAULT_PAGE, DEFAULT_PAGESIZE, Sort.Direction.DESC, "creationTime");

    final List<Device> devicesList = new ArrayList<Device>();
    devicesList.add(this.device);
    this.devices = new PageImpl<Device>(devicesList, this.pageRequest, devicesList.size());

    when(this.deviceRepositoryMock.findAll(this.pageRequest)).thenReturn(this.devices);
    when(this.ssldRepositoryMock.findByDeviceIdentification(any(String.class))).thenReturn(null);
    when(this.ssldRepositoryMock.findOne(any(Long.class))).thenReturn(null);

    final List<DeviceAuthorization> authorizations = new ArrayList<>();
    authorizations.add(new DeviceAuthorizationBuilder().withDevice(this.device)
            .withOrganisation(this.organisation).withFunctionGroup(DeviceFunctionGroup.OWNER).build());
    when(this.deviceAuthorizationRepositoryMock.findByOrganisationAndDevice(this.organisation, this.device))
            .thenReturn(authorizations);
}

From source file:edu.amc.sakai.user.SearchExecutingLdapConnectionLivenessValidator.java

/**
 * Returns localhost's name as reported by
 * {@link InetAddress#getLocalHost()#toString()}. Factored
 * into a method to enable override during testing.
 * //www  . j a  v a 2s  .com
 * @return
 * @throws UnknownHostException
 */
protected String getLocalhostName() throws UnknownHostException {
    return InetAddress.getLocalHost().toString();
}

From source file:com.inmobi.messaging.publisher.AuditService.java

void init(ClientConfig config) throws IOException {
    if (isInit) {
        return;//from  ww w  .  j av a 2  s.c om
    }
    windowSize = config.getInteger(WINDOW_SIZE_KEY, DEFAULT_WINDOW_SIZE);
    aggregateWindowSize = config.getInteger(AGGREGATE_WINDOW_KEY, DEFAULT_AGGREGATE_WINDOW_SIZE);
    executor = new ScheduledThreadPoolExecutor(1);
    try {
        hostname = InetAddress.getLocalHost().getHostName();
    } catch (UnknownHostException e) {
        LOG.error("Unable to find the hostanme of the local box,audit packets" + " won't contain hostname");
        hostname = "";
    }
    worker = new AuditWorker();
    executor.scheduleWithFixedDelay(worker, aggregateWindowSize, aggregateWindowSize, TimeUnit.SECONDS);
    // setting init flag to true
    isInit = true;
}

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

/**
 * thread init method.  This should be called after all the properties
 * have been set./*from  ww w  .  j ava 2s .  c o m*/
 *
 * This should also be the spring init-method.
 * @throws MultiCastResourceBuoyException if the thread fails to start.
 */
public final void startReceiver() throws MultiCastResourceBuoyException {
    if (hostName == null) {
        try {
            hostName = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException ex) {
            throw new MultiCastResourceBuoyException(
                    "Host name not" + " configured, and unable to determine; aborting.");
        }
    }
    log.info("Hostname set to: " + hostName);
    //log.info("Multicast Group: " + get)
    beaconThread = new BeaconMultiCastReceiver();
    new Thread(beaconThread).start();
    //wait for thread to start running, or error out
    while (!beaconThread.isThreadRunning() && !beaconThread.isThreadFailed()) {
        try {
            Thread.sleep(getThreadSleep());
        } catch (InterruptedException ex) {
            log.warn("Thread sleep interupted " + "while waiting on beacon start.");
        }
        if (beaconThread.isThreadFailed()) {
            throw new MultiCastResourceBuoyException(beaconThread.getThrownException().getMessage(),
                    beaconThread.getThrownException());
        }
    }
}

From source file:com.bitbreeds.webrtc.signaling.PeerConnection.java

/**
 *
 * @param offer the received offer/*from  w  w  w  .ja  v  a 2  s  .  co  m*/
 * @return The answer to respond with.
 */
public Answer handleOffer(Offer offer) throws Exception {

    String fingerPrint = CertUtil.getCertFingerPrint(keyStoreInfo.getFilePath(), keyStoreInfo.getAlias(),
            keyStoreInfo.getPassword());

    SessionDescription sdp = offer.getSdp();
    sdp.setAttribute("fingerprint", fingerPrint);
    MediaDescription med = (MediaDescription) sdp.getMediaDescriptions(true).get(0);
    med.setAttribute("fingerprint", fingerPrint);

    String pwd = med.getAttribute("ice-pwd");
    String user = med.getAttribute("ice-ufrag");

    String cand = med.getAttribute("candidate");
    List<String> candData = Arrays.asList(cand.split(" "));

    String ip = candData.get(4);
    String port = candData.get(5);

    this.setRemote(new UserData(user, pwd));

    /**
     * TODO The below should be defined outside PeerConnection
     *
     * This is a huge hack now. Should follow browser API
     * and create datachannel from the outside.
     */
    DataChannelImpl conn = new DataChannelImpl(this);

    //Add handling of input
    conn.onOpen(() -> {
        logger.info("Running onOpen");
        conn.send("I'M SO OPEN!!!");
    });
    conn.onMessage((i) -> {
        String in = new String(i.getData());
        //logger.info("Running onMessage: " + in);
        conn.send("ECHO: " + in);
    });
    conn.onError((i) -> {
        logger.info("Received error", i.getError());
    });

    new Thread(conn).start();

    String localAddress = InetAddress.getLocalHost().getHostAddress();
    String address = System.getProperty("com.bitbreeds.ip", localAddress);
    logger.info("Adr: {}", address);
    med.setAttribute("ice-pwd", local.getPassword());
    med.setAttribute("ice-ufrag", local.getUserName());
    med.setAttribute("candidate", "1 1 UDP 2122252543 " + address + " " + conn.getPort() + " typ host");

    return new Answer(sdp);
}

From source file:com.bright.assetbank.application.servlet.ApplicationActionServlet.java

public void init()/*     */ throws ServletException
/*     */ {/*from  ww  w .j  a  v a 2s . c om*/
    /*     */ try
    /*     */ {
        /*  82 */ setupGlobalSettings();
        /*     */ }
    /*     */ catch (Throwable te)
    /*     */ {
        /*  87 */ System.out.println("ApplicationActionServlet.init: Bn2Exception: " + te.getMessage());
        /*     */ }
    /*     */
    /*  91 */ String[] noStoreActions = getServletConfig().getInitParameter("noStoreGetActions")
            .split("[,\t\n ]+");
    /*  92 */ this.m_noStoreActionSet = new HashSet((int) ((noStoreActions.length + 1) * 1.5D));
    /*  93 */ this.m_noStoreActionSet.addAll(Arrays.asList(noStoreActions));
    /*     */
    /*  95 */ boolean bSuspendLicenseValidation = false;
    /*  96 */ boolean bLicenseValid = false;
    /*  97 */ boolean bLicenseException = false;
    /*  98 */ int iLicenseDaysLeft = 0;
    /*  99 */ String sLicenseDate = "";
    /* 100 */ String sLicenseType = "";
    /* 101 */ boolean bLicenseNeverExpires = false;
    /* 102 */ boolean bLicenseIPUnbound = false;
    /* 103 */ boolean bLicenseWebappUnbound = false;
    /*     */
    /* 106 */ String sLicenseIPs = "";
    /*     */
    /* 109 */ String sLicenseWebapps = "";
    /*     */ try
    /*     */ {
        /* 114 */ LicenseManager licManager = LicenseManager.getInstance();
        /* 115 */ bLicenseValid = licManager.isValid();
        /* 116 */ iLicenseDaysLeft = licManager.daysLeft();
        /* 117 */ sLicenseIPs = licManager.getFeature("IP");
        /* 118 */ sLicenseWebapps = licManager.getFeature("Webapp");
        /* 119 */ sLicenseDate = licManager.getFeature("Expiration");
        /* 120 */ sLicenseType = licManager.getFeature("Type");
        /*     */ }
    /*     */ catch (Throwable e)
    /*     */ {
        /* 124 */ bLicenseValid = false;
        /* 125 */ bLicenseException = true;
        /*     */ }
    /*     */
    /* 128 */ bLicenseNeverExpires = (iLicenseDaysLeft == 0) && ((sLicenseDate == null)
            || (sLicenseDate.length() == 0) || (sLicenseDate.compareToIgnoreCase("never") == 0));
    /* 129 */ bLicenseIPUnbound = (sLicenseIPs == null) || (sLicenseIPs.length() == 0);
    /* 130 */ bLicenseWebappUnbound = (sLicenseWebapps == null) || (sLicenseWebapps.length() == 0);
    /*     */
    /* 133 */ boolean bIPValid = false;
    /* 134 */ boolean bIPException = false;
    /* 135 */ String sLocalIPs = "";
    /* 136 */ Vector vecLocalIPs = new Vector();
    /* 137 */ String sValidIP = "";
    /*     */
    /* 139 */ if (bLicenseIPUnbound)
    /*     */ {
        /* 141 */ bIPValid = true;
        /*     */ }
    /*     */ else
    /*     */ {
        /*     */ try
        /*     */ {
            /* 148 */ Vector vecLicensedIPs = StringUtil.convertToVector(sLicenseIPs, ",");
            /*     */
            /* 151 */ InetAddress ipLocalhost = InetAddress.getLocalHost();
            /* 152 */ InetAddress[] arrAddress = InetAddress.getAllByName(ipLocalhost.getHostName());
            /* 153 */ for (int i = 0; i < arrAddress.length; i++)
            /*     */ {
                /* 158 */ String sIP = arrAddress[i].getHostAddress().trim();
                /* 159 */ vecLocalIPs.add(sIP);
                /* 160 */ sLocalIPs = sLocalIPs + sIP + ", ";
                /*     */ }
            /*     */
            /* 164 */ Iterator it = vecLicensedIPs.iterator();
            /* 165 */ while (it.hasNext())
            /*     */ {
                /* 167 */ String sLicensedIP = (String) it.next();
                /*     */
                /* 169 */ Iterator itLocal = vecLocalIPs.iterator();
                /* 170 */ while (itLocal.hasNext())
                /*     */ {
                    /* 172 */ String sLocalIP = (String) itLocal.next();
                    /*     */
                    /* 174 */ if (sLicensedIP.trim().compareToIgnoreCase(sLocalIP) == 0)
                    /*     */ {
                        /* 176 */ bIPValid = true;
                        /* 177 */ sValidIP = sLocalIP;
                        /* 178 */ break;
                        /*     */ }
                    /*     */ }
                /*     */
                /* 182 */ if (bIPValid)
                /*     */ {
                    /*     */ break;
                    /*     */ }
                /*     */ }
            /*     */
            /*     */ }
        /*     */ catch (UnknownHostException e)
        /*     */ {
            /* 191 */ bIPValid = false;
            /* 192 */ bIPException = true;
            /*     */ }
        /*     */
        /*     */ }
    /*     */
    /* 197 */ boolean bWebappValid = false;
    /* 198 */ String sLocalWebapp = "";
    /*     */
    /* 200 */ if (bLicenseWebappUnbound)
    /*     */ {
        /* 202 */ bWebappValid = true;
        /*     */ }
    /*     */ else
    /*     */ {
        /* 207 */ Vector vecLicensedWebapps = StringUtil.convertToVector(sLicenseWebapps, ",");
        /*     */
        /* 210 */ String sApplicationPath = getServletContext().getRealPath("");
        /* 211 */ File dir = new File(sApplicationPath);
        /* 212 */ sLocalWebapp = dir.getName();
        /*     */
        /* 215 */ Iterator it = vecLicensedWebapps.iterator();
        /* 216 */ while (it.hasNext())
        /*     */ {
            /* 218 */ String sLicensedWebapp = (String) it.next();
            /*     */
            /* 220 */ if (sLicensedWebapp.trim().compareToIgnoreCase(sLocalWebapp) == 0)
            /*     */ {
                /* 222 */ bWebappValid = true;
                /* 223 */ break;
                /*     */ }
            /*     */ }
        /*     */
        /*     */ }
    /*     */
    /* 229 */ boolean bTypeValid = false;
    /*     */
    /* 231 */ bTypeValid = checkLicenseType(sLicenseType);
    /*     */
    /* 234 */ if (((!bLicenseValid) || (!bIPValid) || (!bWebappValid) || (!bTypeValid))
            && (!bSuspendLicenseValidation))
    /*     */ {
        /* 236 */ GlobalApplication.getInstance().suspendWebsite();
        /*     */ }
    /*     */
    /* 240 */ if (AssetBankSettings.isApplicationUpdateInProgress())
    /*     */ {
        /* 243 */ GlobalApplication.getInstance().setSkipStartups(true);
        /*     */ }
    /*     */
    /* 247 */ if (AssetBankSettings.getRequiresEndorsedLibs())
    /*     */ {
        /* 249 */ addEndorsedLibToSystemProperties();
        /*     */ }
    /*     */
    /* 253 */ super.init();
    /*     */
    /* 256 */ if (!bLicenseValid)
    /*     */ {
        /* 258 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: License validation failed.");
        /*     */ }
    /* 260 */ if (bLicenseException)
    /*     */ {
        /* 262 */ GlobalApplication.getInstance().getLogger().error(
                "ApplicationActionServlet.init: Error in license validation is most likely due to missing license file. Check under WEB-INF/classes.");
        /*     */ }
    /* 264 */ if (!bTypeValid)
    /*     */ {
        /* 266 */ GlobalApplication.getInstance().getLogger().info(
                "ApplicationActionServlet.init: License validation failed: License is of the incorrect type");
        /*     */ }
    /* 268 */ if (bIPValid)
    /*     */ {
        /* 270 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License valid for IP address: " + sValidIP);
        /*     */ }
    /*     */ else
    /*     */ {
        /* 274 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: License validation failed: IP address " + sLocalIPs
                        + " not in permitted range: " + sLicenseIPs);
        /*     */ }
    /* 276 */ if (bIPException)
    /*     */ {
        /* 278 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: Error in reading IP address of local host server.");
        /*     */ }
    /* 280 */ if (bWebappValid)
    /*     */ {
        /* 282 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License valid for webapp: " + sLocalWebapp);
        /*     */ }
    /*     */ else
    /*     */ {
        /* 286 */ GlobalApplication.getInstance().getLogger()
                .error("ApplicationActionServlet.init: License validation failed: webapp " + sLocalWebapp
                        + " not in permitted range: " + sLicenseWebapps);
        /*     */ }
    /*     */
    /* 289 */ if ((bLicenseNeverExpires) && (bLicenseValid))
    /*     */ {
        /* 291 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License never expires.");
        /*     */ }
    /*     */ else
    /*     */ {
        /* 295 */ if (iLicenseDaysLeft < 0)
        /*     */ {
            /* 297 */ GlobalApplication.getInstance().getLogger()
                    .error("ApplicationActionServlet.init: License expired!");
            /*     */ }
        /* 299 */ GlobalApplication.getInstance().getLogger()
                .info("ApplicationActionServlet.init: License days left: " + iLicenseDaysLeft);
        /*     */ }
    /*     */
    /* 303 */ GlobalApplication.getInstance().getLogger().info(
            "ApplicationActionServlet.init: Application Version: " + AssetBankSettings.getApplicationVersion());
    /*     */
    /* 307 */ ABUserProfile.setUserProfileFactory(new ABUserProfileFactory());
    /*     */
    /* 312 */ HTTPUtil.setProxySettings();
    /*     */ }

From source file:org.kjkoster.zapcat.test.ZabbixAgentProtocolTest.java

/**
 * Test the we can ping the agent./*w ww.  j  av a  2  s.  com*/
 * 
 * @throws Exception
 *             When the test failed.
 */
@Test
public void testPing() throws Exception {
    final Agent agent = new org.kjkoster.zapcat.zabbix.ZabbixAgent();
    // give the agent some time to open the port
    Thread.sleep(100);
    final Socket socket = new Socket(InetAddress.getLocalHost(),
            org.kjkoster.zapcat.zabbix.ZabbixAgent.DEFAULT_PORT);

    final Writer out = new OutputStreamWriter(socket.getOutputStream());
    out.write("agent.ping\n");
    out.flush();

    final InputStream in = socket.getInputStream();
    final byte[] buffer = new byte[1024];
    final int read = in.read(buffer);
    assertEquals(14, read);

    assertEquals('Z', buffer[0]);
    assertEquals('B', buffer[1]);
    assertEquals('X', buffer[2]);
    assertEquals('D', buffer[3]);

    assertEquals('1', buffer[13]);

    // we'll take the rest for granted...

    socket.close();
    agent.stop();
}

From source file:org.trpr.platform.batch.impl.spring.admin.SimpleJobConfigurationService.java

/**
 * Interface method implementation./*from   www.  j a v a 2 s .  com*/
 * Also sets the hostName
 * @see JobConfigurationService#setPort(int)
 */
@Override
public void setPort(int port) {
    String hostName = "";
    String ipAddr = "";
    try {
        hostName = InetAddress.getLocalHost().getHostName();
        ipAddr = InetAddress.getLocalHost().getHostAddress();
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        //Iterate through all network interfaces
        while (nets.hasMoreElements()) {
            NetworkInterface netint = (NetworkInterface) nets.nextElement();
            Enumeration<InetAddress> ips = netint.getInetAddresses();
            //Iterate through all IP adddress
            while (ips.hasMoreElements()) {
                InetAddress ip = ips.nextElement();
                //Take the first address which isn't a loopback and is in the local address
                if (!ip.isLoopbackAddress() && ip.isSiteLocalAddress()) {
                    LOGGER.info("Host IP Address: " + ip.getHostAddress());
                    ipAddr = ip.getHostAddress();
                    break;
                }
            }
        }
    } catch (UnknownHostException e) {
        LOGGER.error("Error while getting hostName ", e);
    } catch (SocketException e) {
        LOGGER.error("Error while getting hostName ", e);
    }
    this.hostName = new JobHost(hostName, ipAddr, port);
}

From source file:com.chicm.cmraft.core.ClusterMemberManager.java

private void initLocalAddresses() {
    try {//from www  .ja v a  2  s  . c  om
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface inet = (NetworkInterface) interfaces.nextElement();
            Enumeration<InetAddress> addrs = inet.getInetAddresses();
            while (addrs.hasMoreElements()) {
                InetAddress addr = (InetAddress) addrs.nextElement();
                LOG.debug("local address:" + addr.getHostAddress());
                LOG.debug("local address:" + addr.getHostName());
                if (!addr.getHostAddress().isEmpty()) {
                    localAddresses.add(addr.getHostAddress());
                }
                if (!addr.getHostName().isEmpty()) {
                    localAddresses.add(addr.getHostName());
                }
            }
        }

        InetAddress inetAddress = InetAddress.getLocalHost();
        localAddresses.add(inetAddress.getHostAddress());
        localAddresses.add(inetAddress.getCanonicalHostName());
        localAddresses.add(inetAddress.getHostName());

        inetAddress = InetAddress.getLoopbackAddress();
        localAddresses.add(inetAddress.getHostAddress());
        localAddresses.add(inetAddress.getCanonicalHostName());
        localAddresses.add(inetAddress.getHostName());
    } catch (SocketException | UnknownHostException e) {
        LOG.error("", e);
    }
}

From source file:org.eclipse.hono.service.metric.MetricConfig.java

/**
 * Gets a new instance for a graphite reporter.
 * //from  w ww.  j  av  a 2s  .co  m
 * @param period The period to publish the state in milliseconds.
 * @param host The host to report to.
 * @param port The port to report to.
 * @param prefix The prefix used when reporting.
 * 
 * @return The new graphite reporter instance.
 */
@Bean
@ConditionalOnProperty(prefix = "hono.metric.reporter.graphite", name = "active", havingValue = "true")
public GraphiteReporter graphiteReporter(
        @Value("${hono.metric.reporter.graphite.period:5000}") final Long period,
        @Value("${hono.metric.reporter.graphite.host:localhost}") final String host,
        @Value("${hono.metric.reporter.graphite.port:2003}") final Integer port,
        @Value("${hono.metric.reporter.graphite.prefix:}") final String prefix) {
    final Graphite graphite = new Graphite(new InetSocketAddress(host, port));
    String processedPrefix = prefix;
    if (processedPrefix.isEmpty()) {
        try {
            processedPrefix = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException exception) {
            processedPrefix = UNKNOWN;
        }
    }
    LOG.info("metrics - graphite reporter activated: {}:{}  prefix: {}  period: {}", host, port,
            processedPrefix, period);
    final GraphiteReporter reporter = GraphiteReporter.forRegistry(metricRegistry)
            .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).filter(MetricFilter.ALL)
            .prefixedWith(processedPrefix).build(graphite);
    reporter.start(period, TimeUnit.MILLISECONDS);
    return reporter;
}