Example usage for java.net InetAddress getLoopbackAddress

List of usage examples for java.net InetAddress getLoopbackAddress

Introduction

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

Prototype

public static InetAddress getLoopbackAddress() 

Source Link

Document

Returns the loopback address.

Usage

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

private void openHub() {
    try {//from  ww  w  . j  a  v a  2  s  . c o  m
        this.socket = ServerSocketChannel.open();
        this.socket.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), HUB_PORT));
        this.socket.configureBlocking(true);
        this.port = HUB_PORT;
        logger.info("Opened on port: {}", this.port);

    } catch (Exception e) {
        logger.error("Cannot connect because: {}", e.getMessage(), e);
    }
}

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

private void initLocalAddresses() {
    try {//  w  ww  .  j  a v a2s .  com
        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.elasticsearch.client.sniff.ElasticsearchHostsSnifferTests.java

private static HttpServer createHttpServer(final SniffResponse sniffResponse, final int sniffTimeoutMillis)
        throws IOException {
    HttpServer httpServer = MockHttpServer
            .createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
    httpServer.createContext("/_nodes/http", new ResponseHandler(sniffTimeoutMillis, sniffResponse));
    return httpServer;
}

From source file:com.streamsets.pipeline.stage.origin.udp.TestUDPSource.java

private void doBasicTest(UDPDataFormat dataFormat) throws Exception {
    List<String> ports = NetworkUtils.getRandomPorts(2);
    ParserConfig parserConfig = new ParserConfig();
    parserConfig.put(CHARSET, "UTF-8");
    TUDPSource source = new TUDPSource(ports, parserConfig, dataFormat, 20, 100L);
    SourceRunner runner = new SourceRunner.Builder(TUDPSource.class, source).addOutputLane("lane").build();
    runner.runInit();/*from  w  ww.java 2s. co m*/
    try {
        byte[] bytes = null;
        switch (dataFormat) {
        case NETFLOW:
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(TEN_PACKETS_RESOURCE);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(is, baos);
            is.close();
            baos.close();
            bytes = baos.toByteArray();
            break;
        case SYSLOG:
            bytes = "<34>1 2003-10-11T22:14:15.003Z mymachine.example.com some syslog data"
                    .getBytes(StandardCharsets.UTF_8);
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        for (String port : ports) {
            DatagramSocket clientSocket = new DatagramSocket();
            InetAddress address = InetAddress.getLoopbackAddress();
            DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, address,
                    Integer.parseInt(port));
            clientSocket.send(sendPacket);
            clientSocket.close();
        }
        StageRunner.Output output = runner.runProduce(null, 6);
        Assert.assertTrue(source.produceCalled);
        List<Record> records = output.getRecords().get("lane");
        switch (dataFormat) {
        case NETFLOW:
            Assert.assertEquals(String.valueOf(records), 6, records.size());
            break;
        case SYSLOG:
            Assert.assertEquals(String.valueOf(records), ports.size(), records.size());
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        output = runner.runProduce(null, 14);
        Assert.assertTrue(source.produceCalled);
        records = output.getRecords().get("lane");
        switch (dataFormat) {
        case NETFLOW:
            Assert.assertEquals(String.valueOf(records), 14, records.size());
            break;
        case SYSLOG:
            Assert.assertEquals(String.valueOf(records), 0, records.size());
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }
        output = runner.runProduce(null, 1);
        Assert.assertTrue(source.produceCalled);
        records = output.getRecords().get("lane");
        Assert.assertEquals(String.valueOf(records), 0, records.size());
    } finally {
        runner.runDestroy();
    }
}

From source file:org.sonar.ce.cluster.HazelcastClientWrapperImplTest.java

@Test
public void client_must_connect_to_hazelcast() {
    int port = NetworkUtils.getNextAvailablePort(InetAddress.getLoopbackAddress());
    // Launch a fake Hazelcast instance
    HazelcastInstance hzInstance = HazelcastTestHelper
            .createHazelcastCluster("client_must_connect_to_hazelcast", port);
    Settings settings = createClusterSettings("client_must_connect_to_hazelcast", "localhost:" + port);

    HazelcastClientWrapperImpl hazelcastClientWrapperImpl = new HazelcastClientWrapperImpl(settings);
    try {//from w  w w. jav a  2  s .co  m
        hazelcastClientWrapperImpl.start();
        assertThat(hazelcastClientWrapperImpl.getConnectedClients()).hasSize(1);
        assertThat(hazelcastClientWrapperImpl.getClientUUID()).isNotEmpty();
    } finally {
        hazelcastClientWrapperImpl.stop();
    }
}

From source file:com.streamsets.pipeline.stage.origin.udp.BaseUDPSourceTest.java

private void doBasicTest(DatagramMode dataFormat, boolean enableEpoll, int numThreads) throws Exception {

    List<String> ports = NetworkUtils.getRandomPorts(2);
    final UDPSourceConfigBean conf = new UDPSourceConfigBean();

    conf.ports = ports;/*from w ww . j  a va  2  s .  c  om*/
    conf.enableEpoll = enableEpoll;
    conf.numThreads = 1;
    conf.dataFormat = dataFormat;
    conf.maxWaitTime = 1000;
    conf.batchSize = 1000;
    conf.collectdCharset = UTF8;
    conf.syslogCharset = UTF8;
    conf.rawDataCharset = UTF8;

    try {
        byte[] bytes = null;
        switch (dataFormat) {
        case NETFLOW:
            InputStream is = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(TEN_PACKETS_RESOURCE);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(is, baos);
            is.close();
            baos.close();
            bytes = baos.toByteArray();
            break;
        case SYSLOG:
            bytes = RAW_SYSLOG_STR.getBytes(UTF8);

            conf.syslogCharset = UTF8;
            break;
        case RAW_DATA:
            bytes = StringUtils.join(RAW_DATA_VALUES, RAW_DATA_SEPARATOR).getBytes(UTF8);

            conf.rawDataSeparatorBytes = RAW_DATA_SEPARATOR;
            conf.rawDataOutputField = RAW_DATA_OUTPUT_FIELD;
            conf.rawDataCharset = UTF8;
            conf.rawDataMode = RawDataMode.CHARACTER;
            break;
        default:
            Assert.fail("Unknown data format: " + dataFormat);
        }

        initializeRunner(conf, numThreads);

        for (String port : ports) {
            DatagramSocket clientSocket = new DatagramSocket();
            InetAddress address = InetAddress.getLoopbackAddress();
            DatagramPacket sendPacket = new DatagramPacket(bytes, bytes.length, address,
                    Integer.parseInt(port));
            clientSocket.send(sendPacket);
            clientSocket.close();
        }

        runProduce(dataFormat, ports);

    } finally {
        destroyRunner();
    }
}

From source file:de.bieniekconsulting.trafficmonitor.connector.snmp.ConnectorTestCase.java

/**
 * Test getConnection//w w  w.  jav a2  s.c  o m
 *
 * @exception Throwable Thrown if case of an error
 */
@Test
public void testGetConnection1() throws Throwable {
    assertThat(connectionFactory1).isNotNull();
    Snmp4JConnection connection1 = connectionFactory1.getConnection(InetAddress.getLoopbackAddress(),
            "community");
    assertThat(connection1).isNotNull();
    connection1.close();
}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.AbstractApiControllerTest.java

@Before
public void cleanState() {
    super.cleanState();

    try {/* w w  w.  jav  a 2 s .  c o m*/
        try (ServerSocket sock = new ServerSocket(0)) {
            httpServerBaseUri = URI.create(String.format("http://%s:%d/",
                    InetAddressUtils.formatInetAddress(InetAddress.getLoopbackAddress()), sock.getLocalPort()));
        }

        final ResourceConfig rc = new ResourceConfig().registerInstances(Sets.newHashSet(
                new ApiController(factory), new ClusterCleanupController(cluster, factory),
                new ClusterRepairController(cluster, factory),
                new ClusterRollingRestartController(cluster, factory),
                new ClusterBackupController(cluster, factory), new ClusterRestoreController(cluster, factory),
                new ConfigController(cluster, factory), new LiveEndpointsController(cluster, factory),
                new NodeController(cluster, factory), new QaReportController(cluster, factory)));
        httpServer = GrizzlyHttpServerFactory.createHttpServer(httpServerBaseUri, rc);
        httpServer.start();

    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.bookkeeper.util.LocalBookKeeper.java

private void runBookies(ServerConfiguration baseConf, List<File> tempDirs, String dirSuffix) throws IOException,
        KeeperException, InterruptedException, BookieException, UnavailableException, CompatibilityException {
    LOG.info("Starting Bookie(s)");
    // Create Bookie Servers (B1, B2, B3)

    tmpDirs = new File[numberOfBookies];
    bs = new BookieServer[numberOfBookies];
    bsConfs = new ServerConfiguration[numberOfBookies];

    String loopbackIPAddr = InetAddress.getLoopbackAddress().getHostAddress();
    for (int i = 0; i < numberOfBookies; i++) {
        tmpDirs[i] = File.createTempFile("bookie" + Integer.toString(i), "test");
        if (!tmpDirs[i].delete() || !tmpDirs[i].mkdir()) {
            throw new IOException("Couldn't create bookie dir " + tmpDirs[i]);
        }/*from ww  w.j a  v  a 2s. co  m*/

        bsConfs[i] = new ServerConfiguration(baseConf);
        // override settings
        bsConfs[i].setBookiePort(initialPort + i);
        LOG.info("Connecting to Zookeeper at " + loopbackIPAddr + " port:" + ZooKeeperDefaultPort);
        bsConfs[i].setZkServers(loopbackIPAddr + ":" + ZooKeeperDefaultPort);
        bsConfs[i].setJournalDirName(tmpDirs[i].getPath());
        bsConfs[i].setLedgerDirNames(new String[] { tmpDirs[i].getPath() });
        bsConfs[i].setAllowLoopback(true);

        bs[i] = new BookieServer(bsConfs[i]);
        bs[i].start();
    }
}

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

@DomainStep("an authorized device (.*)")
public void givenAnAuthorizedDevice(final String deviceIdentification) {
    LOGGER.info("GIVEN: an authorized device: {}", deviceIdentification);

    // Create the device
    this.device = (Ssld) new DeviceBuilder().withDeviceIdentification(deviceIdentification)
            .withNetworkAddress(InetAddress.getLoopbackAddress()).isActivated(true).build();

    when(this.deviceRepositoryMock.findByDeviceIdentification(deviceIdentification)).thenReturn(this.device);
    when(this.ssldRepositoryMock.findByDeviceIdentification(deviceIdentification)).thenReturn(this.device);
    when(this.ssldRepositoryMock.findOne(1L)).thenReturn(this.device);

    final List<DeviceAuthorization> authorizations = new ArrayList<>();
    authorizations.add(new DeviceAuthorization(this.device, this.organisation, DeviceFunctionGroup.MANAGEMENT));

    when(this.deviceAuthorizationRepositoryMock.findByOrganisationAndDevice(this.organisation, this.device))
            .thenReturn(authorizations);

    final List<DeviceFunction> deviceFunctions = new ArrayList<>();
    deviceFunctions.add(DeviceFunction.GET_EVENT_NOTIFICATIONS);

    when(this.deviceFunctionMappingRepositoryMock.findByDeviceFunctionGroups(any(ArrayList.class)))
            .thenReturn(deviceFunctions);
}