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:google.registry.config.ProductionRegistryConfigExample.java

@Override
public HostAndPort getServer() {
    switch (environment) {
    case LOCAL://w ww .ja v a 2 s .  c o  m
        return HostAndPort.fromParts("localhost", 8080);
    default:
        return HostAndPort.fromParts(String.format("tools-dot-%s.appspot.com", getProjectId()), 443);
    }
}

From source file:brooklyn.location.access.BrooklynAccessUtils.java

public static HostAndPort getBrooklynAccessibleAddress(Entity entity, int port) {
    String host;/*from w w  w.  java2 s  .c  o  m*/

    // look up port forwarding
    PortForwardManager pfw = entity.getConfig(PORT_FORWARDING_MANAGER);
    if (pfw != null) {
        Collection<Location> ll = entity.getLocations();
        Maybe<SupportsPortForwarding> machine = Machines.findUniqueElement(ll, SupportsPortForwarding.class);
        if (machine.isPresent()) {
            synchronized (BrooklynAccessUtils.class) {
                // TODO finer-grained synchronization

                HostAndPort hp = pfw.lookup((MachineLocation) machine.get(), port);
                if (hp != null)
                    return hp;

                Location l = (Location) machine.get();
                if (l instanceof SupportsPortForwarding) {
                    Cidr source = entity.getConfig(MANAGEMENT_ACCESS_CIDR);
                    if (source != null) {
                        log.debug("BrooklynAccessUtils requesting new port-forwarding rule to access " + port
                                + " on " + entity + " (at " + l + ", enabled for " + source + ")");
                        // TODO discuss, is this the best way to do it
                        // (will probably _create_ the port forwarding rule!)
                        hp = ((SupportsPortForwarding) l).getSocketEndpointFor(source, port);
                        if (hp != null)
                            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");
                    }
                }
            }
        }
    }

    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:com.twitter.aurora.scheduler.http.LeaderRedirect.java

private Optional<HostAndPort> getLocalHttp() {
    InetSocketAddress localHttp = serviceRegistry.getAuxiliarySockets().get(HTTP_PORT_NAME);
    return (localHttp == null) ? Optional.<HostAndPort>absent()
            : Optional.of(HostAndPort.fromParts(localHttp.getHostName(), localHttp.getPort()));
}

From source file:io.tsdb.opentsdb.discovery.ConsulPlugin.java

private static void register() {
    AgentClient agentClient = consul.agentClient();

    List<Registration.RegCheck> checks = new ArrayList<Registration.RegCheck>();

    HostAndPort serviceHostAndPort = HostAndPort.fromParts(visibleHost, visiblePort);

    Registration.RegCheck mainCheck = Registration.RegCheck.tcp(serviceHostAndPort.toString(), 30);

    checks.add(mainCheck);/*from  w w w .ja v  a 2  s.  c o  m*/

    Registration registration = ImmutableRegistration.builder().port(visiblePort).address(visibleHost)
            .checks(checks).name(serviceName).id(serviceId).addTags(tsdMode).build();

    agentClient.register(registration);

    if (agentClient.isRegistered(serviceId)) {
        LOGGER.info("Registered this instance with Consul");
    } else {
        LOGGER.warn("Consul reports that this instance is not registered");
    }
}

From source file:org.dcache.xrootd.plugins.ProxyAccessLogHandler.java

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof HAProxyMessage) {
        HAProxyMessage proxyMessage = (HAProxyMessage) msg;
        if (proxyMessage.command() == HAProxyCommand.PROXY) {
            InetSocketAddress remoteAddress = (InetSocketAddress) ctx.channel().remoteAddress();
            InetSocketAddress localAddress = (InetSocketAddress) ctx.channel().localAddress();
            String sourceAddress = proxyMessage.sourceAddress();
            String destinationAddress = proxyMessage.destinationAddress();

            if (proxyMessage.proxiedProtocol() == HAProxyProxiedProtocol.UNKNOWN) {
                NetLoggerBuilder log = new NetLoggerBuilder(INFO, "org.dcache.xrootd.connection.start")
                        .omitNullValues();
                log.add("session", CDC.getSession());
                log.add("socket.remote", remoteAddress);
                log.add("socket.local", localAddress);
                log.toLogger(logger);//  w w  w . ja v  a  2 s  . co m
                replaceWith(ctx, handler);
            } else if (!Objects.equals(destinationAddress, localAddress.getAddress().getHostAddress())) {
                /* The above check is a workaround for what looks like a bug in HAProxy - health checks
                 * should generate a LOCAL command, but it appears they do actually use PROXY.
                 */
                NetLoggerBuilder log = new NetLoggerBuilder(INFO, "org.dcache.xrootd.connection.start")
                        .omitNullValues();
                log.add("session", CDC.getSession());
                log.add("socket.remote", HostAndPort.fromParts(sourceAddress, proxyMessage.sourcePort()));
                log.add("socket.proxy",
                        HostAndPort.fromParts(destinationAddress, proxyMessage.destinationPort()));
                log.add("socket.local", localAddress);
                log.toLogger(logger);
                replaceWith(ctx, handler);
            }
        }
    }
    super.channelRead(ctx, msg);
}

From source file:org.apache.accumulo.monitor.ZooKeeperStatus.java

@Override
public void run() {

    while (!stop) {

        TreeSet<ZooKeeperState> update = new TreeSet<ZooKeeperState>();

        String zookeepers[] = SiteConfiguration.getInstance().get(Property.INSTANCE_ZK_HOST).split(",");
        for (String keeper : zookeepers) {
            int clients = 0;
            String mode = "unknown";

            String[] parts = keeper.split(":");
            TTransport transport = null;
            try {
                HostAndPort addr;/*from  ww w .j  av  a  2s.  c  om*/
                if (parts.length > 1)
                    addr = HostAndPort.fromParts(parts[0], Integer.parseInt(parts[1]));
                else
                    addr = HostAndPort.fromParts(parts[0], 2181);

                transport = TTimeoutTransport.create(addr, 10 * 1000l);
                transport.write("stat\n".getBytes(UTF_8), 0, 5);
                StringBuilder response = new StringBuilder();
                try {
                    transport.flush();
                    byte[] buffer = new byte[1024 * 100];
                    int n = 0;
                    while ((n = transport.read(buffer, 0, buffer.length)) > 0) {
                        response.append(new String(buffer, 0, n, UTF_8));
                    }
                } catch (TTransportException ex) {
                    // happens at EOF
                }
                for (String line : response.toString().split("\n")) {
                    if (line.startsWith(" "))
                        clients++;
                    if (line.startsWith("Mode"))
                        mode = line.split(":")[1];
                }
                update.add(new ZooKeeperState(keeper, mode, clients));
            } catch (Exception ex) {
                log.info("Exception talking to zookeeper " + keeper, ex);
                update.add(new ZooKeeperState(keeper, "Down", -1));
            } finally {
                if (transport != null) {
                    try {
                        transport.close();
                    } catch (Exception ex) {
                        log.error("Exception", ex);
                    }
                }
            }
        }
        status = update;
        sleepUninterruptibly(5, TimeUnit.SECONDS);
    }
}

From source file:domains.donuts.config.DonutsRegistryConfig.java

@Override
public HostAndPort getServer() {
    switch (environment) {
    case LOCAL:/*from   w  w w .j a v  a2s .c o m*/
        return HostAndPort.fromParts("localhost", 8080);
    default:
        String host = Joiner.on(".").join("tools", getProjectId(), "appspot.com");
        return HostAndPort.fromParts(host, 443);
    }
}

From source file:org.jclouds.compute.util.ConcurrentOpenSocketFinder.java

@Override
public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) {
    ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node).transform(new Function<String, HostAndPort>() {

        @Override/*  ww w  .  j  a  va2s.  co  m*/
        public HostAndPort apply(String from) {
            return HostAndPort.fromParts(from, port);
        }
    }).toSet();

    // Specify a retry period of 1s, expressed in the same time units.
    long period = timeUnits.convert(1, TimeUnit.SECONDS);

    // For retrieving the socket found (if any)
    AtomicReference<HostAndPort> result = newReference();

    Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result),
            throwISEIfNoLongerRunning(node));

    logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits);
    boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets);

    if (passed) {
        logger.debug("<< socket %s opened", result);
        assert result.get() != null;
        return result.get();
    } else {
        logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits);
        throw new NoSuchElementException(
                format("could not connect to any ip address port %d on node %s", port, node));
    }

}

From source file:com.smoketurner.dropwizard.consul.ConsulBundle.java

@Override
public void initialize(Bootstrap<?> bootstrap) {
    // Replace variables with values from Consul KV. Please override
    // getConsulAgentHost() and getConsulAgentPort() if Consul is not
    // listening on the default localhost:8500.
    try {/*from   w  w w. ja v  a2s.c o m*/
        final Consul consul = Consul.builder()
                .withHostAndPort(HostAndPort.fromParts(getConsulAgentHost(), getConsulAgentPort())).build();
        bootstrap.setConfigurationSourceProvider(
                new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
                        new ConsulSubstitutor(consul, strict, substitutionInVariables)));
    } catch (ConsulException e) {
        LOGGER.warn("Unable to query Consul running on {}:{}," + " disabling configuration subsitution",
                getConsulAgentHost(), getConsulAgentPort(), e);
    }
}

From source file:com.facebook.swift.service.base.SuiteBase.java

private ListenableFuture<? extends ClientInterface> createClient(ThriftClientManager clientManager)
        throws TTransportException, InterruptedException, ExecutionException {
    HostAndPort address = HostAndPort.fromParts(serverConfig.getBindAddress(), server.getPort());
    return clientManager.createClient(new FramedClientConnector(address), clientClass);
}