Example usage for com.google.common.net HostAndPort fromParts

List of usage examples for com.google.common.net HostAndPort fromParts

Introduction

In this page you can find the example usage for com.google.common.net HostAndPort fromParts.

Prototype

public static HostAndPort fromParts(String host, int port) 

Source Link

Document

Build a HostAndPort instance from separate host and port values.

Usage

From source file:clocker.docker.location.DockerContainerLocation.java

private void mapPort(int hostPort, int containerPort) {
    String dockerHost = getAddress().getHostAddress();
    PortForwardManager portForwardManager = getOwner().getDockerHost().getSubnetTier().getPortForwardManager();
    portForwardManager.associate(dockerHost, HostAndPort.fromParts(dockerHost, hostPort), this, containerPort);
}

From source file:com.facebook.presto.hive.HiveClientModule.java

@Singleton
@Provides/*from w w w. ja  va 2 s.  co  m*/
public HiveCluster createHiveCluster(Injector injector, HivePluginConfig config) {
    URI uri = checkNotNull(config.getMetastoreUri(), "metastoreUri is null");
    String scheme = uri.getScheme();
    checkArgument(!isNullOrEmpty(scheme), "metastoreUri scheme is missing: %s", uri);
    switch (scheme) {
    case "discovery":
        return injector.getInstance(DiscoveryLocatedHiveCluster.class);
    case "thrift":
        checkArgument(uri.getHost() != null, "metastoreUri host is missing: %s", uri);
        checkArgument(uri.getPort() != -1, "metastoreUri port is missing: %s", uri);
        HostAndPort address = HostAndPort.fromParts(uri.getHost(), uri.getPort());
        return new StaticHiveCluster(address, injector.getInstance(HiveMetastoreClientFactory.class));
    }
    throw new IllegalArgumentException("unsupported metastoreUri: " + uri);
}

From source file:org.springframework.xd.ec2.cloud.AWSInstanceChecker.java

private boolean verifyResourceAddress(String addresses) {
    SocketOpen socketOpen = computeService.getContext().utils().injector().getInstance(SocketOpen.class);
    Predicate<HostAndPort> socketTester = retry(socketOpen, 180, 1, TimeUnit.SECONDS);
    boolean result = false;
    String[] addressList = StringUtils.commaDelimitedListToStringArray(addresses);
    for (String address : addressList) {
        String[] tokens = StringUtils.delimitedListToStringArray(address, ":");
        if (socketTester.apply(HostAndPort.fromParts(tokens[0], Integer.valueOf(tokens[1])))) {
            result = true;//  w w w  . j a v  a 2  s.co  m
            break;
        }

    }
    return result;
}

From source file:org.apache.accumulo.proxy.Proxy.java

@Override
public void execute(final String[] args) throws Exception {
    Opts opts = new Opts();
    opts.parseArgs(Proxy.class.getName(), args);

    boolean useMini = Boolean
            .parseBoolean(opts.prop.getProperty(USE_MINI_ACCUMULO_KEY, USE_MINI_ACCUMULO_DEFAULT));
    boolean useMock = Boolean
            .parseBoolean(opts.prop.getProperty(USE_MOCK_INSTANCE_KEY, USE_MOCK_INSTANCE_DEFAULT));
    String instance = opts.prop.getProperty(ACCUMULO_INSTANCE_NAME_KEY);
    String zookeepers = opts.prop.getProperty(ZOOKEEPERS_KEY);

    if (!useMini && !useMock && instance == null) {
        System.err.println(//from   w ww . jav  a 2s. com
                "Properties file must contain one of : useMiniAccumulo=true, useMockInstance=true, or instance=<instance name>");
        System.exit(1);
    }

    if (instance != null && zookeepers == null) {
        System.err.println("When instance is set in properties file, zookeepers must also be set.");
        System.exit(1);
    }

    if (!opts.prop.containsKey("port")) {
        System.err.println("No port property");
        System.exit(1);
    }

    if (useMini) {
        log.info("Creating mini cluster");
        final File folder = Files.createTempDir();
        final MiniAccumuloCluster accumulo = new MiniAccumuloCluster(folder, "secret");
        accumulo.start();
        opts.prop.setProperty("instance", accumulo.getConfig().getInstanceName());
        opts.prop.setProperty("zookeepers", accumulo.getZooKeepers());
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void start() {
                try {
                    accumulo.stop();
                } catch (Exception e) {
                    throw new RuntimeException();
                } finally {
                    if (!folder.delete())
                        log.warn("Unexpected error removing " + folder);
                }
            }
        });
    }

    Class<? extends TProtocolFactory> protoFactoryClass = Class
            .forName(opts.prop.getProperty("protocolFactory", TCompactProtocol.Factory.class.getName()))
            .asSubclass(TProtocolFactory.class);
    TProtocolFactory protoFactory = protoFactoryClass.newInstance();
    int port = Integer.parseInt(opts.prop.getProperty("port"));
    String hostname = opts.prop.getProperty(THRIFT_SERVER_HOSTNAME, THRIFT_SERVER_HOSTNAME_DEFAULT);
    HostAndPort address = HostAndPort.fromParts(hostname, port);
    ServerAddress server = createProxyServer(address, protoFactory, opts.prop);
    // Wait for the server to come up
    while (!server.server.isServing()) {
        Thread.sleep(100);
    }
    log.info("Proxy server started on " + server.getAddress());
    while (server.server.isServing()) {
        Thread.sleep(1000);
    }
}

From source file:brooklyn.entity.mesos.framework.marathon.MarathonPortForwarder.java

@Override
public HostAndPort openPortForwarding(HostAndPort targetSide, Optional<Integer> optionalPublicPort,
        Protocol protocol, Cidr accessingCidr) {
    PortForwardManager pfw = getPortForwardManager();
    HostAndPort publicSide;//from  www .  j a v  a  2  s. c  o  m
    if (optionalPublicPort.isPresent()) {
        int publicPort = optionalPublicPort.get();
        publicSide = HostAndPort.fromParts(marathonHostname, publicPort);
    } else {
        publicSide = HostAndPort.fromParts(marathonHostname, targetSide.getPort());
    }
    pfw.associate(marathonHostname, publicSide, targetSide.getPort());
    portmap.put(publicSide, targetSide);
    return publicSide;
}

From source file:org.apache.druid.server.DruidNode.java

/**
 * Returns host and port together as something that can be used as part of a URI.
 *//*from  w ww.  j  a va 2  s  .c o m*/
public String getHostAndPort() {
    if (enablePlaintextPort) {
        if (plaintextPort < 0) {
            return HostAndPort.fromString(host).toString();
        } else {
            return HostAndPort.fromParts(host, plaintextPort).toString();
        }
    }
    return null;
}

From source file:org.apache.kudu.client.MiniKuduCluster.java

/**
 * Start the specified number of masters with ports starting from the specified
 * number. Finds free web and RPC ports up front for all of the masters first, then
 * starts them on those ports.//  w w w . j a v a2s.  c o  m
 *
 * @param startPort the starting point of the port range for the masters
 * @param numServers number of master servers to start
 * @param baseDirPath the base directory where the mini cluster stores its data
 * @return the next free port
 * @throws Exception if we are unable to start the masters
 */
private int startMasters(int startPort, int numServers, String baseDirPath, String bindHost) throws Exception {
    if (numServers <= 0) {
        return startPort;
    }
    // Get the list of web and RPC ports to use for the master consensus configuration:
    // request NUM_MASTERS * 2 free ports as we want to also reserve the web
    // ports for the consensus configuration.
    final List<Integer> ports = TestUtils.findFreePorts(startPort > 0 ? startPort : PORT_START, numServers * 2);
    List<Integer> masterRpcPorts = Lists.newArrayListWithCapacity(numServers);
    List<Integer> masterWebPorts = Lists.newArrayListWithCapacity(numServers);
    for (int i = 0; i < numServers * 2; i++) {
        if (i % 2 == 0) {
            masterRpcPorts.add(ports.get(i));
            masterHostPorts.add(HostAndPort.fromParts(bindHost, ports.get(i)));
        } else {
            masterWebPorts.add(ports.get(i));
        }
    }
    masterAddresses = NetUtil.hostsAndPortsToString(masterHostPorts);
    long now = System.currentTimeMillis();
    for (int i = 0; i < numServers; i++) {
        int port = masterRpcPorts.get(i);
        String masterBaseDirPath = baseDirPath + "/master-" + i + "-" + now;
        new File(masterBaseDirPath).mkdir();
        String logDirPath = masterBaseDirPath + "/logs";
        new File(logDirPath).mkdir();
        String dataDirPath = masterBaseDirPath + "/data";
        String flagsPath = TestUtils.getFlagsPath();
        // The web port must be reserved in the call to findFreePorts above and specified
        // to avoid the scenario where:
        // 1) findFreePorts finds RPC ports a, b, c for the 3 masters.
        // 2) start master 1 with RPC port and let it bind to any (specified as 0) web port.
        // 3) master 1 happens to bind to port b for the web port, as master 2 hasn't been
        // started yet and findFreePort(s) is "check-time-of-use" (it does not reserve the
        // ports, only checks that when it was last called, these ports could be used).
        List<String> commandLine = Lists.newArrayList(TestUtils.findBinary("kudu-master"),
                "--flagfile=" + flagsPath, "--log_dir=" + logDirPath, "--fs_wal_dir=" + dataDirPath,
                "--fs_data_dirs=" + dataDirPath, "--ipki_ca_key_size=1024", "--ipki_server_key_size=1024",
                "--tsk_num_rsa_bits=512", "--webserver_interface=" + bindHost,
                "--local_ip_for_outbound_sockets=" + bindHost, "--rpc_bind_addresses=" + bindHost + ":" + port,
                "--webserver_port=" + masterWebPorts.get(i), "--raft_heartbeat_interval_ms=200"); // make leader elections faster for faster tests

        if (numServers > 1) {
            commandLine.add("--master_addresses=" + masterAddresses);
        }

        if (miniKdc != null) {
            commandLine.add("--keytab_file=" + keytab);
            commandLine.add("--principal=kudu/" + bindHost);
            commandLine.add("--rpc_authentication=required");
            commandLine.add("--superuser_acl=testuser");
        }

        commandLine.addAll(extraMasterFlags);

        masterProcesses.put(port, configureAndStartProcess(port, commandLine));
        commandLines.put(port, commandLine);

        if (flagsPath.startsWith(baseDirPath)) {
            // We made a temporary copy of the flags; delete them later.
            pathsToDelete.add(flagsPath);
        }
        pathsToDelete.add(masterBaseDirPath);
    }
    // Return next port number.
    return ports.get(ports.size() - 1) + 1;
}

From source file:org.apache.druid.server.DruidNode.java

public String getHostAndTlsPort() {
    if (enableTlsPort) {
        return HostAndPort.fromParts(host, tlsPort).toString();
    }
    return null;
}

From source file:brooklyn.networking.vclouddirector.PortForwarderVcloudDirector.java

@Override
public HostAndPort openPortForwarding(HostAndPort targetEndpoint, Optional<Integer> optionalPublicPort,
        Protocol protocol, Cidr accessingCidr) {
    // TODO should associate ip:port with PortForwardManager; but that takes location param
    //      getPortForwardManager().associate(publicIp, publicPort, targetVm, targetPort);
    // TODO Could check old mapping, and re-use that public port
    // TODO Pass cidr in vcloud-director call
    String publicIp = subnetTier.getConfig(NETWORK_PUBLIC_IP);

    HostAndPort publicEndpoint;/* w  ww.  ja  v  a 2 s.c o m*/
    PortRange portRangeToUse;
    if (optionalPublicPort.isPresent()) {
        publicEndpoint = HostAndPort.fromParts(publicIp, optionalPublicPort.get());
        portRangeToUse = null;
    } else if (getNatMicroserviceAutoAllocatesPorts()) {
        publicEndpoint = HostAndPort.fromString(publicIp);
        portRangeToUse = getPortRange();
    } else {
        PortForwardManager pfw = getPortForwardManager();
        int publicPort = pfw.acquirePublicPort(publicIp);
        publicEndpoint = HostAndPort.fromParts(publicIp, publicPort);
        portRangeToUse = null;
    }

    try {
        HostAndPort result = getClient().openPortForwarding(new PortForwardingConfig().protocol(Protocol.TCP)
                .publicEndpoint(publicEndpoint).publicPortRange(portRangeToUse).targetEndpoint(targetEndpoint));

        // TODO Work around for old vCD NAT microservice, which returned empty result
        if (!result.hasPort() && result.getHostText().equals("")) {
            if (publicEndpoint.hasPort()) {
                LOG.warn(
                        "[DEPRECATED] NAT Rule addition returned endpoint '{}'; probably old micro-service version; "
                                + "assuming result is {}->{} via {}",
                        new Object[] { result, publicEndpoint, targetEndpoint, subnetTier });
                result = publicEndpoint;
            } else {
                throw new IllegalStateException("Invalid result for NAT Rule addition, returned endpoint ''; "
                        + "cannot infer actual result as no explicit port requested for " + publicEndpoint
                        + "->" + targetEndpoint + " via " + subnetTier);
            }
        }

        LOG.debug("Enabled port-forwarding for {}, via {}, on ",
                new Object[] { targetEndpoint, result, subnetTier });
        return result;
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        LOG.info("Failed creating port forwarding rule on " + this + ": " + publicEndpoint + "->"
                + targetEndpoint + "; rethrowing", e);
        throw Exceptions.propagate(e);
    }
}

From source file:brooklyn.util.internal.ssh.sshj.SshjTool.java

protected SshjTool(Builder<?, ?> builder) {
    super(builder);

    sshTries = builder.sshTries;//from w w  w  .j  av a 2  s  . com
    sshTriesTimeout = builder.sshTriesTimeout;
    backoffLimitedRetryHandler = new BackoffLimitedRetryHandler(sshTries, builder.sshRetryDelay);

    sshClientConnection = SshjClientConnection.builder().hostAndPort(HostAndPort.fromParts(host, port))
            .username(user).password(password).privateKeyPassphrase(privateKeyPassphrase)
            .privateKeyData(privateKeyData).privateKeyFile(privateKeyFile)
            .strictHostKeyChecking(strictHostKeyChecking).connectTimeout(builder.connectTimeout)
            .sessionTimeout(builder.sessionTimeout).build();

    if (LOG.isTraceEnabled())
        LOG.trace("Created SshTool {} ({})", this, System.identityHashCode(this));
}