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:org.springframework.xd.integration.util.StreamUtils.java

private static SshjSshClient getSSHClient(String host, String privateKey) {
    final LoginCredentials credential = LoginCredentials.fromCredentials(new Credentials("ubuntu", privateKey));
    final HostAndPort socket = HostAndPort.fromParts(host, 22);
    final SshjSshClient client = new SshjSshClient(new BackoffLimitedRetryHandler(), socket, credential, 5000);
    return client;
}

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

public void run(String hostname) {
    try {/*w w w  .  j a v a2 s  .com*/
        getMonitorLock();
    } catch (Exception e) {
        log.error("Failed to get Monitor ZooKeeper lock");
        throw new RuntimeException(e);
    }

    Monitor.START_TIME = System.currentTimeMillis();
    int port = config.getConfiguration().getPort(Property.MONITOR_PORT);
    try {
        log.debug("Creating monitor on port " + port);
        server = new EmbeddedWebServer(hostname, port);
    } catch (Throwable ex) {
        log.error("Unable to start embedded web server", ex);
        throw new RuntimeException(ex);
    }

    server.addServlet(DefaultServlet.class, "/");
    server.addServlet(OperationServlet.class, "/op");
    server.addServlet(MasterServlet.class, "/master");
    server.addServlet(TablesServlet.class, "/tables");
    server.addServlet(TServersServlet.class, "/tservers");
    server.addServlet(ProblemServlet.class, "/problems");
    server.addServlet(GcStatusServlet.class, "/gc");
    server.addServlet(LogServlet.class, "/log");
    server.addServlet(XMLServlet.class, "/xml");
    server.addServlet(JSONServlet.class, "/json");
    server.addServlet(VisServlet.class, "/vis");
    server.addServlet(ScanServlet.class, "/scans");
    server.addServlet(BulkImportServlet.class, "/bulkImports");
    server.addServlet(Summary.class, "/trace/summary");
    server.addServlet(ListType.class, "/trace/listType");
    server.addServlet(ShowTrace.class, "/trace/show");
    server.addServlet(ReplicationServlet.class, "/replication");
    if (server.isUsingSsl())
        server.addServlet(ShellServlet.class, "/shell");
    server.start();

    try {
        log.debug("Using " + hostname + " to advertise monitor location in ZooKeeper");

        String monitorAddress = HostAndPort.fromParts(hostname, server.getPort()).toString();

        ZooReaderWriter.getInstance().putPersistentData(
                ZooUtil.getRoot(instance) + Constants.ZMONITOR_HTTP_ADDR, monitorAddress.getBytes(UTF_8),
                NodeExistsPolicy.OVERWRITE);
        log.info("Set monitor address in zookeeper to " + monitorAddress);
    } catch (Exception ex) {
        log.error("Unable to set monitor HTTP address in zookeeper", ex);
    }

    if (null != hostname) {
        LogService.startLogListener(Monitor.getContext().getConfiguration(), instance.getInstanceID(),
                hostname);
    } else {
        log.warn("Not starting log4j listener as we could not determine address to use");
    }

    new Daemon(new LoggingRunnable(log, new ZooKeeperStatus()), "ZooKeeperStatus").start();

    // need to regularly fetch data so plot data is updated
    new Daemon(new LoggingRunnable(log, new Runnable() {

        @Override
        public void run() {
            while (true) {
                try {
                    Monitor.fetchData();
                } catch (Exception e) {
                    log.warn("{}", e.getMessage(), e);
                }

                sleepUninterruptibly(333, TimeUnit.MILLISECONDS);
            }

        }
    }), "Data fetcher").start();

    new Daemon(new LoggingRunnable(log, new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Monitor.fetchScans();
                } catch (Exception e) {
                    log.warn("{}", e.getMessage(), e);
                }
                sleepUninterruptibly(5, TimeUnit.SECONDS);
            }
        }
    }), "Scan scanner").start();
}

From source file:org.apache.brooklyn.entity.nosql.cassandra.CassandraDatacenterImpl.java

@Override
public void update() {
    synchronized (mutex) {
        // Update our seeds, as necessary
        seedTracker.refreshSeeds();/*from  www  .j ava2s .  com*/

        // Choose the first available cluster member to set host and port (and compute one-up)
        Optional<Entity> upNode = Iterables.tryFind(getMembers(),
                EntityPredicates.attributeEqualTo(SERVICE_UP, Boolean.TRUE));

        if (upNode.isPresent()) {
            sensors().set(HOSTNAME, upNode.get().getAttribute(Attributes.HOSTNAME));
            sensors().set(THRIFT_PORT, upNode.get().getAttribute(CassandraNode.THRIFT_PORT));

            List<String> currentNodes = getAttribute(CASSANDRA_CLUSTER_NODES);
            Set<String> oldNodes = (currentNodes != null) ? ImmutableSet.copyOf(currentNodes)
                    : ImmutableSet.<String>of();
            Set<String> newNodes = MutableSet.<String>of();
            for (Entity member : getMembers()) {
                if (member instanceof CassandraNode && Boolean.TRUE.equals(member.getAttribute(SERVICE_UP))) {
                    String hostname = member.getAttribute(Attributes.HOSTNAME);
                    Integer thriftPort = member.getAttribute(CassandraNode.THRIFT_PORT);
                    if (hostname != null && thriftPort != null) {
                        newNodes.add(HostAndPort.fromParts(hostname, thriftPort).toString());
                    }
                }
            }
            if (Sets.symmetricDifference(oldNodes, newNodes).size() > 0) {
                sensors().set(CASSANDRA_CLUSTER_NODES, MutableList.copyOf(newNodes));
            }
        } else {
            sensors().set(HOSTNAME, null);
            sensors().set(THRIFT_PORT, null);
            sensors().set(CASSANDRA_CLUSTER_NODES, Collections.<String>emptyList());
        }

        ServiceNotUpLogic.updateNotUpIndicatorRequiringNonEmptyList(this, CASSANDRA_CLUSTER_NODES);
    }
}

From source file:org.apache.accumulo.server.monitor.Monitor.java

public void run(String hostname) {
    Monitor.START_TIME = System.currentTimeMillis();
    int port = config.getConfiguration().getPort(Property.MONITOR_PORT);
    try {/* ww  w .ja  v a 2s .com*/
        log.debug("Creating monitor on port " + port);
        server = new EmbeddedWebServer(hostname, port);
    } catch (Throwable ex) {
        log.error("Unable to start embedded web server", ex);
        throw new RuntimeException(ex);
    }

    server.addServlet(DefaultServlet.class, "/");
    server.addServlet(OperationServlet.class, "/op");
    server.addServlet(MasterServlet.class, "/master");
    server.addServlet(TablesServlet.class, "/tables");
    server.addServlet(TServersServlet.class, "/tservers");
    server.addServlet(ProblemServlet.class, "/problems");
    server.addServlet(GcStatusServlet.class, "/gc");
    server.addServlet(LogServlet.class, "/log");
    server.addServlet(XMLServlet.class, "/xml");
    server.addServlet(JSONServlet.class, "/json");
    server.addServlet(VisServlet.class, "/vis");
    server.addServlet(Summary.class, "/trace/summary");
    server.addServlet(ListType.class, "/trace/listType");
    server.addServlet(ShowTrace.class, "/trace/show");
    if (server.isUsingSsl())
        server.addServlet(ShellServlet.class, "/shell");
    server.start();

    try {
        String monitorAddress = HostAndPort.fromParts(hostname, server.getPort()).toString();
        ZooReaderWriter.getInstance().putPersistentData(ZooUtil.getRoot(instance) + Constants.ZMONITOR,
                monitorAddress.getBytes(), NodeExistsPolicy.OVERWRITE);
        log.info("Set monitor address in zookeeper to " + monitorAddress);
    } catch (Exception ex) {
        log.error("Unable to set monitor address in zookeeper");
    }
    LogService.startLogListener(Monitor.getSystemConfiguration(), instance.getInstanceID());

    new Daemon(new LoggingRunnable(log, new ZooKeeperStatus()), "ZooKeeperStatus").start();

    // need to regularly fetch data so plot data is updated
    new Daemon(new LoggingRunnable(log, new Runnable() {

        @Override
        public void run() {
            while (true) {
                try {
                    Monitor.fetchData();
                } catch (Exception e) {
                    log.warn(e.getMessage(), e);
                }

                UtilWaitThread.sleep(333);
            }

        }
    }), "Data fetcher").start();
}

From source file:org.apache.brooklyn.location.basic.SshMachineLocation.java

public HostAndPort getSshHostAndPort() {
    String host = getConfig(SSH_HOST);
    if (host == null || Strings.isEmpty(host))
        host = address.getHostName();/*from w w  w .j a v  a  2 s.c o m*/
    Integer port = getConfig(SSH_PORT);
    if (port == null || port == 0)
        port = 22;
    return HostAndPort.fromParts(host, port);
}

From source file:org.apache.brooklyn.location.ssh.SshMachineLocation.java

public HostAndPort getSshHostAndPort() {
    String host = getConfig(SSH_HOST);
    if (host == null || Strings.isEmpty(host))
        host = address.getHostName();//from   w  ww.ja  v a  2 s .  c  om
    Integer port = getPort();
    return HostAndPort.fromParts(host, port);
}

From source file:beans.ServerBootstrapperImpl.java

static public ExecResponse runScriptOnNode(Conf conf, String serverIP, String script)
        throws NumberFormatException, IOException {
    logger.debug("Run ssh on server: {} script: {}", serverIP, script);
    Injector i = Guice.createInjector(new SshjSshClientModule(), new NullLoggingModule());
    SshClient.Factory factory = i.getInstance(SshClient.Factory.class);
    SshClient sshConnection = factory.create(HostAndPort.fromParts(serverIP, conf.server.bootstrap.ssh.port),
            LoginCredentials.builder().user(conf.server.bootstrap.ssh.user)
                    .privateKey(Strings2
                            .toStringAndClose(new FileInputStream(conf.server.bootstrap.ssh.privateKey)))
                    .build());/*from   w  w w.j a  va2 s.  c o  m*/
    ExecResponse execResponse = null;
    try {
        sshConnection.connect();
        logger.info("ssh connected, executing");
        execResponse = sshConnection.exec(script);
        logger.info("finished execution");
    } finally {
        if (sshConnection != null)
            sshConnection.disconnect();
    }

    return execResponse;
}

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

/**
 * Start the appropriate Thrift server (SSL or non-blocking server) for the given parameters. Non-null SSL parameters will cause an SSL server to be started.
 *
 * @return A ServerAddress encapsulating the Thrift server created and the host/port which it is bound to.
 *///from  ww  w. j av a2 s  .c  o  m
public static ServerAddress startTServer(HostAndPort address, ThriftServerType serverType,
        TimedProcessor processor, TProtocolFactory protocolFactory, String serverName, String threadName,
        int numThreads, int numSTThreads, long timeBetweenThreadChecks, long maxMessageSize,
        SslConnectionParams sslParams, SaslServerConnectionParams saslParams, long serverSocketTimeout)
        throws TTransportException {

    // This is presently not supported. It's hypothetically possible, I believe, to work, but it would require changes in how the transports
    // work at the Thrift layer to ensure that both the SSL and SASL handshakes function. SASL's quality of protection addresses privacy issues.
    checkArgument(!(sslParams != null && saslParams != null),
            "Cannot start a Thrift server using both SSL and SASL");

    ServerAddress serverAddress;
    switch (serverType) {
    case SSL:
        log.debug("Instantiating SSL Thrift server");
        serverAddress = createSslThreadPoolServer(address, processor, protocolFactory, serverSocketTimeout,
                sslParams, serverName, numThreads, numSTThreads, timeBetweenThreadChecks);
        break;
    case SASL:
        log.debug("Instantiating SASL Thrift server");
        serverAddress = createSaslThreadPoolServer(address, processor, protocolFactory, serverSocketTimeout,
                saslParams, serverName, threadName, numThreads, numSTThreads, timeBetweenThreadChecks);
        break;
    case THREADPOOL:
        log.debug("Instantiating unsecure TThreadPool Thrift server");
        serverAddress = createBlockingServer(address, processor, protocolFactory, maxMessageSize, serverName,
                numThreads, numSTThreads, timeBetweenThreadChecks);
        break;
    case CUSTOM_HS_HA: // Intentional passthrough -- Our custom wrapper around HsHa is the default
    default:
        log.debug("Instantiating default, unsecure custom half-async Thrift server");
        serverAddress = createNonBlockingServer(address, processor, protocolFactory, serverName, threadName,
                numThreads, numSTThreads, timeBetweenThreadChecks, maxMessageSize);
    }

    final TServer finalServer = serverAddress.server;
    Runnable serveTask = new Runnable() {
        @Override
        public void run() {
            try {
                finalServer.serve();
            } catch (Error e) {
                Halt.halt("Unexpected error in TThreadPoolServer " + e + ", halting.");
            }
        }
    };

    serveTask = new LoggingRunnable(TServerUtils.log, serveTask);
    Thread thread = new Daemon(serveTask, threadName);
    thread.start();

    // check for the special "bind to everything address"
    if (serverAddress.address.getHostText().equals("0.0.0.0")) {
        // can't get the address from the bind, so we'll do our best to invent our hostname
        try {
            serverAddress = new ServerAddress(finalServer, HostAndPort
                    .fromParts(InetAddress.getLocalHost().getHostName(), serverAddress.address.getPort()));
        } catch (UnknownHostException e) {
            throw new TTransportException(e);
        }
    }
    return serverAddress;
}

From source file:org.apache.brooklyn.container.location.kubernetes.KubernetesLocation.java

protected void registerPortMappings(KubernetesSshMachineLocation machine, Entity entity, Service service) {
    PortForwardManager portForwardManager = (PortForwardManager) getManagementContext().getLocationRegistry()
            .getLocationManaged(PortForwardManagerLocationResolver.PFM_GLOBAL_SPEC);
    List<ServicePort> ports = service.getSpec().getPorts();
    String publicHostText = ((SshMachineLocation) machine).getSshHostAndPort().getHostText();
    LOG.debug("Recording port-mappings for container {} of {}: {}", new Object[] { machine, this, ports });

    for (ServicePort port : ports) {
        String protocol = port.getProtocol();
        Integer targetPort = port.getTargetPort().getIntVal();

        if (!"TCP".equalsIgnoreCase(protocol)) {
            LOG.debug("Ignoring port mapping {} for {} because only TCP is currently supported", port, machine);
        } else if (targetPort == null) {
            LOG.debug("Ignoring port mapping {} for {} because targetPort.intValue is null", port, machine);
        } else if (port.getNodePort() == null) {
            LOG.debug("Ignoring port mapping {} to {} because port.getNodePort() is null", targetPort, machine);
        } else {//from www . j a  va 2  s . c  om
            portForwardManager.associate(publicHostText,
                    HostAndPort.fromParts(publicHostText, port.getNodePort()), machine, targetPort);
            AttributeSensor<Integer> sensor = Sensors.newIntegerSensor(
                    "kubernetes." + Strings.maybeNonBlank(port.getName()).or(targetPort.toString()) + ".port");
            entity.sensors().set(sensor, targetPort);
        }
    }

    entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class)
            .configure(OnPublicNetworkEnricher.MAP_MATCHING, "kubernetes.[a-zA-Z0-9][a-zA-Z0-9-_]*.port"));
}

From source file:org.apache.accumulo.gc.SimpleGarbageCollector.java

private HostAndPort startStatsService() throws UnknownHostException {
    Iface rpcProxy = RpcWrapper.service(this, new Processor<Iface>(this));
    final Processor<Iface> processor;
    if (ThriftServerType.SASL == getThriftServerType()) {
        Iface tcProxy = TCredentialsUpdatingWrapper.service(rpcProxy, getClass(), getConfiguration());
        processor = new Processor<Iface>(tcProxy);
    } else {/*  w  ww  .j  av  a  2 s  . c om*/
        processor = new Processor<Iface>(rpcProxy);
    }
    int port = getConfiguration().getPort(Property.GC_PORT);
    long maxMessageSize = getConfiguration().getMemoryInBytes(Property.GENERAL_MAX_MESSAGE_SIZE);
    HostAndPort result = HostAndPort.fromParts(opts.getAddress(), port);
    log.debug("Starting garbage collector listening on " + result);
    try {
        return TServerUtils.startTServer(getConfiguration(), result, getThriftServerType(), processor,
                this.getClass().getSimpleName(), "GC Monitor Service", 2,
                getConfiguration().getCount(Property.GENERAL_SIMPLETIMER_THREADPOOL_SIZE), 1000, maxMessageSize,
                getServerSslParams(), getSaslParams(), 0).address;
    } catch (Exception ex) {
        // ACCUMULO-3651 Level changed to error and FATAL added to message for slf4j compatibility
        log.error("FATAL:", ex);
        throw new RuntimeException(ex);
    }
}