Java Code Examples for com.google.common.net.HostAndPort#fromParts()

The following examples show how to use com.google.common.net.HostAndPort#fromParts() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: KafkaLowLevelConsumer09.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private HostAndPort findNewLeader(HostAndPort oldLeader, String topic, int partition) throws StageException {
  //try 3 times to find a new leader
  for (int i = 0; i < 3; i++) {
    boolean sleep;
    PartitionMetadata metadata = getPartitionMetadata(replicaBrokers, topic, partition);
    if (metadata == null || metadata.leader() == null) {
      sleep = true;
    } else if (oldLeader.getHostText().equalsIgnoreCase(metadata.leader().host()) && i == 0) {
      //leader has not yet changed, give zookeeper sometime
      sleep = true;
    } else {
      return HostAndPort.fromParts(metadata.leader().host(), metadata.leader().port());
    }
    if (sleep) {
      ThreadUtil.sleep(ONE_SECOND);
    }
  }
  LOG.error(KafkaErrors.KAFKA_21.getMessage());
  throw new StageException(KafkaErrors.KAFKA_21);
}
 
Example 2
Source File: TestDriftNettyServerTransport.java    From drift with Apache License 2.0 6 votes vote down vote up
private static int testServerMethodInvoker(ServerMethodInvoker methodInvoker, boolean assumeClientsSupportOutOfOrderResponses, List<ToIntFunction<HostAndPort>> clients)
{
    DriftNettyServerConfig config = new DriftNettyServerConfig()
            .setAssumeClientsSupportOutOfOrderResponses(assumeClientsSupportOutOfOrderResponses);
    TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator();
    ServerTransport serverTransport = new DriftNettyServerTransportFactory(config, testingAllocator).createServerTransport(methodInvoker);
    try {
        serverTransport.start();

        HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) serverTransport).getPort());

        int sum = 0;
        for (ToIntFunction<HostAndPort> client : clients) {
            sum += client.applyAsInt(address);
        }
        return sum;
    }
    finally {
        serverTransport.shutdown();
        testingAllocator.close();
    }
}
 
Example 3
Source File: TestServerRule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
protected void before() throws InterruptedException {
  try {
    testServer =
        new TestServer(
            HostAndPort.fromParts(
                // Use external IP address here so the browser running inside Docker container
                // can access this server.
                getExternalAddressOfLocalSystem().getHostAddress(), pickUnusedPort()),
            runfiles,
            routes,
            filters);
  } catch (UnknownHostException e) {
    throw new IllegalStateException(e);
  }
  setIsAdmin(false);
  Server server = new Server();
  serverThread = new Thread(server);
  synchronized (this) {
    serverThread.start();
    while (!server.isRunning) {
      this.wait();
    }
  }
}
 
Example 4
Source File: TestConnectionPool.java    From drift with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectionClosed()
{
    try (ConnectionPool pool = new ConnectionPool(new TestingConnectionManager(), new DefaultEventLoopGroup(), 10, new Duration(1, MINUTES))) {
        HostAndPort address = HostAndPort.fromParts("localhost", 1234);

        Channel channel1 = futureGet(pool.getConnection(PARAMETERS, address));
        assertTrue(channel1.isOpen());
        channel1.close();
        assertFalse(channel1.isOpen());

        Channel channel2 = futureGet(pool.getConnection(PARAMETERS, address));
        assertTrue(channel2.isOpen());
        assertNotSame(channel1, channel2);
    }
}
 
Example 5
Source File: HostAndPortDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@Override
public HostAndPort deserialize(JsonParser p, DeserializationContext ctxt)
    throws IOException
{
    // Need to override this method, which otherwise would work just fine,
    // since we have legacy JSON Object format to support too:
    if (p.hasToken(JsonToken.START_OBJECT)) { // old style
        JsonNode root = p.readValueAsTree();
        // [datatypes-collections#45]: we actually have 2 possibilities depending on Guava version
        JsonNode hostNode = root.get("host");
        final String host = (hostNode == null) ? root.path("hostText").asText() : hostNode.textValue();
        JsonNode n = root.get("port");
        if (n == null) {
            return HostAndPort.fromString(host);
        }
        return HostAndPort.fromParts(host, n.asInt());
    }
    return super.deserialize(p, ctxt);
}
 
Example 6
Source File: PushGatewayProviderTest.java    From graylog-plugin-metrics-reporter with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void getReturnsPushGatewayProvider() throws Exception {
    final MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_ACCEPTED));
    server.start();

    final MetricsPrometheusReporterConfiguration configuration = new MetricsPrometheusReporterConfiguration() {
        @Override
        public HostAndPort getAddress() {
            return HostAndPort.fromParts(server.getHostName(), server.getPort());
        }
    };
    final PushGatewayProvider provider = new PushGatewayProvider(configuration);
    final PushGateway pushGateway = provider.get();
    pushGateway.push(CollectorRegistry.defaultRegistry, "test");

    final RecordedRequest request = server.takeRequest();
    assertEquals("PUT", request.getMethod());
    assertEquals("/metrics/job/test", request.getPath());
    assertEquals("text/plain; version=0.0.4; charset=utf-8", request.getHeader("Content-Type"));
    assertEquals(0L, request.getBodySize());
}
 
Example 7
Source File: LeaderRedirectTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedirectTargetQueryString() throws Exception {
  HttpServletRequest mockRequest = mockRequest(null, "bar=baz");

  replayAndMonitor(1);

  HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT);
  publishSchedulers(remote);

  assertEquals(
      Optional.of("http://foobar:500/some/path?bar=baz"),
      leaderRedirector.getRedirectTarget(mockRequest));
}
 
Example 8
Source File: JcloudsLocationReleasePortForwardingDefaultTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public HostAndPort openPortForwarding(NodeMetadata node, int targetPort, Optional<Integer> optionalPublicPort, Protocol protocol, Cidr accessingCidr) {
    calls.add(ImmutableList.of("open", Duration.of(stopwatch), node, targetPort, optionalPublicPort, protocol, accessingCidr));
    Time.sleep(sleepBeforeReturning);
    if (optionalPublicPort.isPresent()) {
        return HostAndPort.fromParts("2.2.2.2", optionalPublicPort.get());
    } else {
        return HostAndPort.fromParts("2.2.2.2", nextPort.get());
    }
}
 
Example 9
Source File: LeaderRedirectTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testNotLeader() throws Exception {
  replayAndMonitor(3);

  HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT);
  publishSchedulers(remote);

  assertEquals(Optional.of(remote), leaderRedirector.getRedirect());

  // NB: NOT_LEADING takes 2 tests of the server group membership to calculate; thus we expect 3
  // server group get calls, 1 for the getRedirect() above and 2 here.
  assertEquals(LeaderStatus.NOT_LEADING, leaderRedirector.getLeaderStatus());
}
 
Example 10
Source File: HostProxy.java    From styx with Apache License 2.0 5 votes vote down vote up
private static HostAndPort addDefaultPort(HostAndPort hostAndPort, TlsSettings tlsSettings) {
    if (hostAndPort.hasPort()) {
        return hostAndPort;
    }

    int defaultPort = Optional.ofNullable(tlsSettings)
            .map(it -> DEFAULT_TLS_PORT)
            .orElse(DEFAULT_HTTP_PORT);

    return HostAndPort.fromParts(hostAndPort.getHost(), defaultPort);
}
 
Example 11
Source File: TestApacheThriftMethodInvoker.java    From drift with Apache License 2.0 5 votes vote down vote up
private static int testProcessor(TProcessor processor, List<ToIntFunction<HostAndPort>> clients)
        throws Exception
{
    try (TServerSocket serverTransport = new TServerSocket(0)) {
        TProtocolFactory protocolFactory = new Factory();
        TTransportFactory transportFactory = new TFramedTransport.Factory();
        TServer server = new TSimpleServer(new Args(serverTransport)
                .protocolFactory(protocolFactory)
                .transportFactory(transportFactory)
                .processor(processor));

        Thread serverThread = new Thread(server::serve);
        try {
            serverThread.start();

            int localPort = serverTransport.getServerSocket().getLocalPort();
            HostAndPort address = HostAndPort.fromParts("localhost", localPort);

            int sum = 0;
            for (ToIntFunction<HostAndPort> client : clients) {
                sum += client.applyAsInt(address);
            }
            return sum;
        }
        finally {
            server.stop();
            serverThread.interrupt();
        }
    }
}
 
Example 12
Source File: BrooklynAccessUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort) {
    HostAndPort result = mappings.get(privatePort);
    if (result == null) {
        int publicPort = nextPort.getAndIncrement();
        result = HostAndPort.fromParts(publicIp, publicPort);
        mappings.put(privatePort, result);
    }
    return result;
}
 
Example 13
Source File: ReferrerTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
ServerResource() {
  this.server = new Server();

  ServerConnector http = new ServerConnector(server);
  int port = PortProber.findFreePort();
  http.setPort(port);
  http.setIdleTimeout(500000);

  this.server.addConnector(http);

  this.hostAndPort = HostAndPort.fromParts(JettyAppServer.detectHostname(), port);
}
 
Example 14
Source File: LeaderRedirectTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedirectTargetWithAttribute() throws Exception {
  HttpServletRequest mockRequest = mockRequest("/the/original/path", null);

  replayAndMonitor(1);

  HostAndPort remote = HostAndPort.fromParts("foobar", HTTP_PORT);
  publishSchedulers(remote);

  assertEquals(
      Optional.of("http://foobar:500/the/original/path"),
      leaderRedirector.getRedirectTarget(mockRequest));
}
 
Example 15
Source File: MockThriftMetastoreClientFactory.java    From presto with Apache License 2.0 4 votes vote down vote up
private static HostAndPort createHostAndPort(String str)
{
    URI uri = URI.create(str);
    return HostAndPort.fromParts(uri.getHost(), uri.getPort());
}
 
Example 16
Source File: PortAccessorConfiguration.java    From soabase with Apache License 2.0 4 votes vote down vote up
@Override
public HostAndPort getMainPort(Configuration configuration)
{
    return HostAndPort.fromParts("x", 1);
}
 
Example 17
Source File: KafkaConsumerConfig.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
/**
 * @param host the host to set
 */
public void setHost(String host) {
   this.broker = HostAndPort.fromParts(host, this.broker.getPort());
}
 
Example 18
Source File: TestingKuduServer.java    From presto with Apache License 2.0 4 votes vote down vote up
public HostAndPort getMasterAddress()
{
    return HostAndPort.fromParts(master.getContainerIpAddress(), master.getMappedPort(KUDU_MASTER_PORT));
}
 
Example 19
Source File: TestEndpointReachableTest.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected HostAndPort toHostAndPort(ServerSocket ss) {
    return HostAndPort.fromParts(serverSocket.getInetAddress().getHostAddress(), serverSocket.getLocalPort());
}
 
Example 20
Source File: PrometheusServer.java    From presto with Apache License 2.0 4 votes vote down vote up
public HostAndPort getAddress()
{
    return HostAndPort.fromParts(dockerContainer.getContainerIpAddress(), dockerContainer.getMappedPort(PROMETHEUS_PORT));
}