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:com.streamsets.pipeline.kafka.impl.KafkaLowLevelConsumer09.java

@Override
public void init() throws StageException {
    List<HostAndPort> brokers = new ArrayList<>();
    brokers.add(broker);//from  www .  j a  v a  2 s. com
    PartitionMetadata metadata = getPartitionMetadata(brokers, topic, partition);
    if (metadata == null) {
        LOG.error(KafkaErrors.KAFKA_23.getMessage(), topic, partition);
        throw new StageException(KafkaErrors.KAFKA_23, topic, partition);
    }
    if (metadata.leader() == null) {
        LOG.error(KafkaErrors.KAFKA_24.getMessage(), topic, partition);
        throw new StageException(KafkaErrors.KAFKA_24, topic, partition);
    }
    leader = HostAndPort.fromParts(metadata.leader().host(), metadata.leader().port());
    //recreate consumer instance with the leader information for that topic
    LOG.info(
            "Creating SimpleConsumer using the following configuration: host {}, port {}, max wait time {}, max "
                    + "fetch size {}, client columnName {}",
            leader.getHostText(), leader.getPort(), maxWaitTime, maxFetchSize, clientName);
    consumer = new SimpleConsumer(leader.getHostText(), leader.getPort(), maxWaitTime, maxFetchSize,
            clientName);
}

From source file:com.proofpoint.jmx.JmxAgent.java

@VisibleForTesting
static HostAndPort getRunningAgentAddress(Integer registryPort, Integer serverPort) {
    try {/*from  w  ww. j  a  v  a  2s. co  m*/
        JMXConnectorServer jmxServer = getField(Agent.class, JMXConnectorServer.class, "jmxServer");
        RemoteObject registry = getField(ConnectorBootstrap.class, RemoteObject.class, "registry");

        if (jmxServer != null && registry != null) {
            int actualRegistryPort = ((UnicastRef) registry.getRef()).getLiveRef().getPort();

            checkState(actualRegistryPort > 0, "Expected actual RMI registry port to be > 0, actual: %s",
                    actualRegistryPort);

            // if registry port and server port were configured and the agent is already running, make sure
            // the configuration agrees to avoid surprises
            if (registryPort != null && registryPort != 0) {
                checkArgument(actualRegistryPort == registryPort,
                        "JMX agent is already running, but actual RMI registry port (%s) doesn't match configured port (%s)",
                        actualRegistryPort, registryPort);
            }

            if (serverPort != null && serverPort != 0) {
                int actualServerPort = jmxServer.getAddress().getPort();
                checkArgument(actualServerPort == serverPort,
                        "JMX agent is already running, but actual RMI server port (%s) doesn't match configured port (%s)",
                        actualServerPort, serverPort);
            }

            return HostAndPort.fromParts(jmxServer.getAddress().getHost(), actualRegistryPort);
        }
    } catch (Exception e) {
        log.warn(e, "Cannot determine if JMX agent is already running. Will try to start it manually.");
    }

    return null;
}

From source file:org.jclouds.rds.xml.InstanceHandler.java

/**
 * {@inheritDoc}//from w  w w.ja  v a2 s.  co m
 */
@Override
public void endElement(String uri, String name, String qName) throws SAXException {

    if (equalsOrSuffix(qName, "DBSubnetGroup")) {
        builder.subnetGroup(subnetGroupHandler.getResult());
        inSubnetGroup = false;
    } else if (inSubnetGroup) {
        subnetGroupHandler.endElement(uri, name, qName);
    } else if (equalsOrSuffix(qName, "DBInstanceIdentifier")) {
        builder.id(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "InstanceCreateTime")) {
        builder.createdTime(dateService.iso8601DateParse(currentOrNull(currentText)));
    } else if (equalsOrSuffix(qName, "DBName")) {
        builder.name(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "AllocatedStorage")) {
        builder.allocatedStorageGB(Integer.parseInt(currentOrNull(currentText)));
    } else if (equalsOrSuffix(qName, "DBInstanceStatus")) {
        String rawStatus = currentOrNull(currentText);
        builder.rawStatus(rawStatus);
        builder.status(Instance.Status.fromValue(rawStatus));
    } else if (equalsOrSuffix(qName, "Address")) {
        address = currentOrNull(currentText);
    } else if (equalsOrSuffix(qName, "Port")) {
        port = Integer.valueOf(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "Endpoint")) {
        // sometimes in deleting state, address is null while port isn't
        if (address != null && port != null)
            builder.endpoint(HostAndPort.fromParts(address, port));
        address = null;
        port = null;
    } else if (equalsOrSuffix(qName, "DBSecurityGroupName")) {
        groupName = currentOrNull(currentText);
    } else if (equalsOrSuffix(qName, "Status")) {
        status = currentOrNull(currentText);
    } else if (equalsOrSuffix(qName, "DBSecurityGroup")) {
        securityGroupBuilder.put(groupName, status);
        groupName = status = null;
    } else if (equalsOrSuffix(qName, "DBSecurityGroups")) {
        builder.securityGroupNameToStatus(securityGroupBuilder.build());
        securityGroupBuilder = ImmutableMap.<String, String>builder();
    } else if (equalsOrSuffix(qName, "DBInstanceClass")) {
        builder.instanceClass(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "AvailabilityZone")) {
        builder.availabilityZone(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "MultiAZ")) {
        builder.multiAZ(Boolean.parseBoolean(currentOrNull(currentText)));
    } else if (equalsOrSuffix(qName, "Engine")) {
        builder.engine(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "EngineVersion")) {
        builder.engineVersion(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "LicenseModel")) {
        builder.licenseModel(currentOrNull(currentText));
    } else if (equalsOrSuffix(qName, "MasterUsername")) {
        builder.masterUsername(currentOrNull(currentText));
    }
    currentText = new StringBuilder();
}

From source file:io.druid.server.DruidNode.java

/**
 * Returns host and port together as something that can be used as part of a URI.
 *///  w  w  w .jav  a 2 s  .c  om
public String getHostAndPort() {
    if (port < 0) {
        return HostAndPort.fromString(host).toString();
    } else {
        return HostAndPort.fromParts(host, port).toString();
    }
}

From source file:org.apache.accumulo.server.util.LocalityCheck.java

private void addBlocks(VolumeManager fs, String host, ArrayList<String> files, Map<String, Long> totalBlocks,
        Map<String, Long> localBlocks) throws Exception {
    long allBlocks = 0;
    long matchingBlocks = 0;
    if (!totalBlocks.containsKey(host)) {
        totalBlocks.put(host, 0L);//w  ww  .  j a v a2 s .  c o m
        localBlocks.put(host, 0L);
    }
    for (String file : files) {
        Path filePath = new Path(file);
        FileSystem ns = fs.getVolumeByPath(filePath).getFileSystem();
        FileStatus fileStatus = ns.getFileStatus(filePath);
        BlockLocation[] fileBlockLocations = ns.getFileBlockLocations(fileStatus, 0, fileStatus.getLen());
        for (BlockLocation blockLocation : fileBlockLocations) {
            allBlocks++;
            for (String location : blockLocation.getHosts()) {
                HostAndPort hap = HostAndPort.fromParts(location, 0);
                if (hap.getHostText().equals(host)) {
                    matchingBlocks++;
                    break;
                }
            }
        }
    }
    totalBlocks.put(host, allBlocks + totalBlocks.get(host));
    localBlocks.put(host, matchingBlocks + localBlocks.get(host));
}

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

@Override
public void openFirewallPort(Entity entity, int port, Protocol protocol, Cidr accessingCidr) {
    LOG.debug("Open iptables rule for {}, {}, {}, {}",
            new Object[] { this, entity, port, protocol, accessingCidr });
    if (cluster.config().get(MesosCluster.SDN_ENABLE)) {
        HostAndPort target = portmap.get(HostAndPort.fromParts(marathonHostname, port));
        addIptablesRule(port, target);/*from   w ww  . ja  v a  2 s  .c o m*/
        String profile = entity.getApplicationId(); // TODO allow other Calico profiles
        String command = BashCommands.sudo(String.format(
                "calicoctl profile %s rule add inbound allow tcp to ports %d", profile, target.getPort()));
        CalicoModule calico = (CalicoModule) cluster.sensors().get(MesosCluster.SDN_PROVIDER);
        calico.execCalicoCommand(slave, command);
    }
}

From source file:org.apache.brooklyn.core.location.access.BrooklynAccessUtils.java

public static HostAndPort getBrooklynAccessibleAddress(Entity entity, int port) {
    String host;//from   ww w .  ja v a  2s. c om

    // look up port forwarding
    PortForwardManager pfw = entity.getConfig(PORT_FORWARDING_MANAGER);
    if (pfw != null) {
        Collection<Location> ll = entity.getLocations();

        synchronized (BrooklynAccessUtils.class) {
            // TODO finer-grained synchronization

            for (MachineLocation machine : Iterables.filter(ll, MachineLocation.class)) {
                HostAndPort hp = pfw.lookup(machine, port);
                if (hp != null) {
                    log.debug(
                            "BrooklynAccessUtils found port-forwarded address {} for entity {}, port {}, using machine {}",
                            new Object[] { hp, entity, port, machine });
                    return hp;
                }
            }

            Maybe<SupportsPortForwarding> supportPortForwardingLoc = Machines.findUniqueElement(ll,
                    SupportsPortForwarding.class);
            if (supportPortForwardingLoc.isPresent()) {
                Cidr source = entity.getConfig(MANAGEMENT_ACCESS_CIDR);
                SupportsPortForwarding loc = supportPortForwardingLoc.get();
                if (source != null) {
                    log.debug("BrooklynAccessUtils requesting new port-forwarding rule to access " + port
                            + " on " + entity + " (at " + loc + ", enabled for " + source + ")");
                    // TODO discuss, is this the best way to do it
                    // (will probably _create_ the port forwarding rule!)
                    HostAndPort hp = loc.getSocketEndpointFor(source, port);
                    if (hp != null) {
                        log.debug(
                                "BrooklynAccessUtils created port-forwarded address {} for entity {}, port {}, using {}",
                                new Object[] { hp, entity, port, loc });
                        return hp;
                    }
                } else {
                    log.warn("No " + MANAGEMENT_ACCESS_CIDR.getName() + " configured for " + entity
                            + ", so cannot forward " + "port " + port + " " + "even though "
                            + PORT_FORWARDING_MANAGER.getName() + " was supplied, and "
                            + "have location supporting port forwarding " + loc);
                }
            }
        }
    }

    host = entity.getAttribute(Attributes.HOSTNAME);
    if (host != null)
        return HostAndPort.fromParts(host, port);

    throw new IllegalStateException(
            "Cannot find way to access port " + port + " on " + entity + " from Brooklyn (no host.name)");
}

From source file:org.apache.accumulo.server.util.TServerUtils.java

/**
 * Start a server, at the given port, or higher, if that port is not available.
 * //  w  ww  . j  a v a  2 s.c  o  m
 * @param portHintProperty
 *          the port to attempt to open, can be zero, meaning "any available port"
 * @param processor
 *          the service to be started
 * @param serverName
 *          the name of the class that is providing the service
 * @param threadName
 *          name this service's thread for better debugging
 * @return the server object created, and the port actually used
 * @throws UnknownHostException
 *           when we don't know our own address
 */
public static ServerAddress startServer(AccumuloConfiguration conf, String address, Property portHintProperty,
        TProcessor processor, String serverName, String threadName, Property portSearchProperty,
        Property minThreadProperty, Property timeBetweenThreadChecksProperty, Property maxMessageSizeProperty)
        throws UnknownHostException {
    int portHint = conf.getPort(portHintProperty);
    int minThreads = 2;
    if (minThreadProperty != null)
        minThreads = conf.getCount(minThreadProperty);
    long timeBetweenThreadChecks = 1000;
    if (timeBetweenThreadChecksProperty != null)
        timeBetweenThreadChecks = conf.getTimeInMillis(timeBetweenThreadChecksProperty);
    long maxMessageSize = 10 * 1000 * 1000;
    if (maxMessageSizeProperty != null)
        maxMessageSize = conf.getMemoryInBytes(maxMessageSizeProperty);
    boolean portSearch = false;
    if (portSearchProperty != null)
        portSearch = conf.getBoolean(portSearchProperty);
    // create the TimedProcessor outside the port search loop so we don't try to register the same metrics mbean more than once
    TServerUtils.TimedProcessor timedProcessor = new TServerUtils.TimedProcessor(processor, serverName,
            threadName);
    Random random = new Random();
    for (int j = 0; j < 100; j++) {

        // Are we going to slide around, looking for an open port?
        int portsToSearch = 1;
        if (portSearch)
            portsToSearch = 1000;

        for (int i = 0; i < portsToSearch; i++) {
            int port = portHint + i;
            if (portHint != 0 && i > 0)
                port = 1024 + random.nextInt(65535 - 1024);
            if (port > 65535)
                port = 1024 + port % (65535 - 1024);
            try {
                HostAndPort addr = HostAndPort.fromParts(address, port);
                return TServerUtils.startTServer(addr, timedProcessor, serverName, threadName, minThreads,
                        timeBetweenThreadChecks, maxMessageSize, SslConnectionParams.forServer(conf),
                        conf.getTimeInMillis(Property.GENERAL_RPC_TIMEOUT));
            } catch (TTransportException ex) {
                log.error("Unable to start TServer", ex);
                if (ex.getCause() == null || ex.getCause().getClass() == BindException.class) {
                    // Note: with a TNonblockingServerSocket a "port taken" exception is a cause-less
                    // TTransportException, and with a TSocket created by TSSLTransportFactory, it
                    // comes through as caused by a BindException.
                    log.info("Unable to use port " + port + ", retrying. (Thread Name = " + threadName + ")");
                    UtilWaitThread.sleep(250);
                } else {
                    // thrift is passing up a nested exception that isn't a BindException,
                    // so no reason to believe retrying on a different port would help.
                    log.error("Unable to start TServer", ex);
                    break;
                }
            }
        }
    }
    throw new UnknownHostException("Unable to find a listen port");
}

From source file:io.airlift.jmx.JmxAgent.java

@VisibleForTesting
static HostAndPort getRunningAgentAddress(Integer registryPort, Integer serverPort) {
    JMXConnectorServer jmxServer;
    RemoteObject registry;//from w  ww.j  a  va 2  s  .  co m
    int actualRegistryPort;
    try {
        jmxServer = getField(Agent.class, JMXConnectorServer.class, "jmxServer");
        registry = getField(ConnectorBootstrap.class, RemoteObject.class, "registry");

        if (jmxServer == null || registry == null) {
            log.warn(
                    "Cannot determine if JMX agent is already running (not an Oracle JVM?). Will try to start it manually.");
            return null;
        }

        actualRegistryPort = ((UnicastRef) registry.getRef()).getLiveRef().getPort();
    } catch (Exception e) {
        log.warn(e, "Cannot determine if JMX agent is already running. Will try to start it manually.");
        return null;
    }

    checkState(actualRegistryPort > 0, "Expected actual RMI registry port to be > 0, actual: %s",
            actualRegistryPort);

    // if registry port and server port were configured and the agent is already running, make sure
    // the configuration agrees to avoid surprises
    if (registryPort != null && registryPort != 0) {
        checkArgument(actualRegistryPort == registryPort,
                "JMX agent is already running, but actual RMI registry port (%s) doesn't match configured port (%s)",
                actualRegistryPort, registryPort);
    }

    if (serverPort != null && serverPort != 0) {
        int actualServerPort = jmxServer.getAddress().getPort();
        checkArgument(actualServerPort == serverPort,
                "JMX agent is already running, but actual RMI server port (%s) doesn't match configured port (%s)",
                actualServerPort, serverPort);
    }

    return HostAndPort.fromParts(jmxServer.getAddress().getHost(), actualRegistryPort);
}

From source file:clocker.docker.networking.entity.sdn.calico.CalicoNodeSshDriver.java

@Override
public Map<String, String> getShellEnvironment() {
    Entity etcdNode = getEntity().config().get(CalicoNode.ETCD_NODE);
    HostAndPort etcdAuthority = HostAndPort.fromParts(etcdNode.sensors().get(Attributes.SUBNET_ADDRESS),
            etcdNode.sensors().get(EtcdNode.ETCD_CLIENT_PORT));
    Map<String, String> environment = MutableMap.copyOf(super.getShellEnvironment());
    environment.put("ETCD_AUTHORITY", etcdAuthority.toString());
    return environment;
}