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

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

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Get the current port number, failing if no port is defined.

Usage

From source file:de.uniulm.omi.cloudiator.sword.core.ssh.jsch.JSchSessionFactoryImpl.java

@Override
public Session getSession(HostAndPort hostAndPort, LoginCredential loginCredential) throws JSchException {
    if (loginCredential.isPrivateKeyCredential()) {
        this.jSch.addIdentity(loginCredential.privateKey().get());
    }//w  w w  . jav  a 2 s.  c o m
    Session session = this.jSch.getSession(loginCredential.username(), hostAndPort.getHostText(),
            hostAndPort.getPort());
    if (loginCredential.isPasswordCredential()) {
        session.setPassword(loginCredential.password().get());
    }
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();

    return session;
}

From source file:org.apache.accumulo.server.watcher.MonitorLog4jWatcher.java

/**
 * Read the host and port information for the Monitor's log4j socket and update the system properties so that, on logger refresh, it sees the new information.
 *///from  ww w .  j a va  2s.c  om
protected void updateMonitorLog4jLocation() {
    try {
        String hostPortString = new String(ZooReaderWriter.getInstance().getData(path, null), UTF_8);
        HostAndPort hostAndPort = HostAndPort.fromString(hostPortString);

        System.setProperty(HOST_PROPERTY_NAME, hostAndPort.getHostText());
        System.setProperty(PORT_PROPERTY_NAME, Integer.toString(hostAndPort.getPort()));

        log.info("Changing monitor log4j address to " + hostAndPort.toString());

        doOnChange();
    } catch (NoNodeException e) {
        // Not sure on the synchronization guarantees for Loggers and Appenders
        // on configuration reload
        synchronized (lock) {
            // Don't need to try to re-disable'ing it.
            if (loggingDisabled) {
                return;
            }

            Logger logger = LogManager.getLogger("org.apache.accumulo");
            if (null != logger) {
                // TODO ACCUMULO-2343 Create a specific appender for log-forwarding to the monitor
                // that can replace the AsyncAppender+SocketAppender.
                Appender appender = logger.getAppender("ASYNC");
                if (null != appender) {
                    log.info("Closing log-forwarding appender");
                    appender.close();
                    log.info("Removing log-forwarding appender");
                    logger.removeAppender(appender);
                    loggingDisabled = true;
                }
            }
        }
    } catch (IllegalArgumentException e) {
        log.error("Could not parse host and port information", e);
    } catch (Exception e) {
        log.error("Error reading zookeeper data for Monitor Log4j watcher", e);
    }
}

From source file:org.apache.brooklyn.entity.webapp.JavaWebAppSshDriver.java

protected String inferRootUrl() {
    if (isProtocolEnabled("https")) {
        Integer port = getHttpsPort();
        checkNotNull(port, "HTTPS_PORT sensors not set; is an acceptable port available?");
        HostAndPort accessibleAddress = BrooklynAccessUtils.getBrooklynAccessibleAddress(getEntity(), port);
        return String.format("https://%s:%s/", accessibleAddress.getHostText(), accessibleAddress.getPort());
    } else if (isProtocolEnabled("http")) {
        Integer port = getHttpPort();
        checkNotNull(port, "HTTP_PORT sensors not set; is an acceptable port available?");
        HostAndPort accessibleAddress = BrooklynAccessUtils.getBrooklynAccessibleAddress(getEntity(), port);
        return String.format("http://%s:%s/", accessibleAddress.getHostText(), accessibleAddress.getPort());
    } else {//from www.  j  av a2 s . c  om
        throw new IllegalStateException("HTTP and HTTPS protocols not enabled for " + entity
                + "; enabled protocols are " + getEnabledProtocols());
    }
}

From source file:org.apache.accumulo.core.rpc.ThriftUtil.java

/**
 * Create a TTransport for clients to the given address with the provided socket timeout and session-layer configuration
 *
 * @param address/*  w  w  w  . j a v  a2 s  .com*/
 *          Server address to connect to
 * @param timeout
 *          Client socket timeout
 * @param sslParams
 *          RPC options for SSL servers
 * @param saslParams
 *          RPC options for SASL servers
 * @return An open TTransport which must be closed when finished
 */
public static TTransport createClientTransport(HostAndPort address, int timeout, SslConnectionParams sslParams,
        SaslConnectionParams saslParams) throws TTransportException {
    boolean success = false;
    TTransport transport = null;
    try {
        if (sslParams != null) {
            // The check in AccumuloServerContext ensures that servers are brought up with sane configurations, but we also want to validate clients
            if (null != saslParams) {
                throw new IllegalStateException("Cannot use both SSL and SASL");
            }

            log.trace("Creating SSL client transport");

            // TSSLTransportFactory handles timeout 0 -> forever natively
            if (sslParams.useJsse()) {
                transport = TSSLTransportFactory.getClientSocket(address.getHostText(), address.getPort(),
                        timeout);
            } else {
                // JDK6's factory doesn't appear to pass the protocol onto the Socket properly so we have
                // to do some magic to make sure that happens. Not an issue in JDK7

                // Taken from thrift-0.9.1 to make the SSLContext
                SSLContext sslContext = createSSLContext(sslParams);

                // Create the factory from it
                SSLSocketFactory sslSockFactory = sslContext.getSocketFactory();

                // Wrap the real factory with our own that will set the protocol on the Socket before returning it
                ProtocolOverridingSSLSocketFactory wrappingSslSockFactory = new ProtocolOverridingSSLSocketFactory(
                        sslSockFactory, new String[] { sslParams.getClientProtocol() });

                // Create the TSocket from that
                transport = createClient(wrappingSslSockFactory, address.getHostText(), address.getPort(),
                        timeout);
                // TSSLTransportFactory leaves transports open, so no need to open here
            }

            transport = ThriftUtil.transportFactory().getTransport(transport);
        } else if (null != saslParams) {
            if (!UserGroupInformation.isSecurityEnabled()) {
                throw new IllegalStateException("Expected Kerberos security to be enabled if SASL is in use");
            }

            log.trace("Creating SASL connection to {}:{}", address.getHostText(), address.getPort());

            // Make sure a timeout is set
            try {
                transport = TTimeoutTransport.create(address, timeout);
            } catch (IOException e) {
                log.warn("Failed to open transport to {}", address);
                throw new TTransportException(e);
            }

            try {
                // Log in via UGI, ensures we have logged in with our KRB credentials
                final UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();

                // Is this pricey enough that we want to cache it?
                final String hostname = InetAddress.getByName(address.getHostText()).getCanonicalHostName();

                final SaslMechanism mechanism = saslParams.getMechanism();

                log.trace("Opening transport to server as {} to {}/{} using {}", currentUser,
                        saslParams.getKerberosServerPrimary(), hostname, mechanism);

                // Create the client SASL transport using the information for the server
                // Despite the 'protocol' argument seeming to be useless, it *must* be the primary of the server being connected to
                transport = new TSaslClientTransport(mechanism.getMechanismName(), null,
                        saslParams.getKerberosServerPrimary(), hostname, saslParams.getSaslProperties(),
                        saslParams.getCallbackHandler(), transport);

                // Wrap it all in a processor which will run with a doAs the current user
                transport = new UGIAssumingTransport(transport, currentUser);

                // Open the transport
                transport.open();
            } catch (TTransportException e) {
                log.warn("Failed to open SASL transport", e);

                // We might have had a valid ticket, but it expired. We'll let the caller retry, but we will attempt to re-login to make the next attempt work.
                // Sadly, we have no way to determine the actual reason we got this TTransportException other than inspecting the exception msg.
                log.debug(
                        "Caught TTransportException opening SASL transport, checking if re-login is necessary before propagating the exception.");
                attemptClientReLogin();

                throw e;
            } catch (IOException e) {
                log.warn("Failed to open SASL transport", e);
                throw new TTransportException(e);
            }
        } else {
            log.trace("Opening normal transport");
            if (timeout == 0) {
                transport = new TSocket(address.getHostText(), address.getPort());
                transport.open();
            } else {
                try {
                    transport = TTimeoutTransport.create(address, timeout);
                } catch (IOException ex) {
                    log.warn("Failed to open transport to " + address);
                    throw new TTransportException(ex);
                }

                // Open the transport
                transport.open();
            }
            transport = ThriftUtil.transportFactory().getTransport(transport);
        }
        success = true;
    } finally {
        if (!success && transport != null) {
            transport.close();
        }
    }
    return transport;
}

From source file:org.apache.aurora.scheduler.http.LeaderRedirect.java

/**
 * Gets the optional redirect URI target in the event that this process is not the leading
 * scheduler./*from   w ww  .  j  a v a2s  .c  o  m*/
 *
 * @param req HTTP request.
 * @return An optional redirect destination to route the request to the leading scheduler.
 */
Optional<String> getRedirectTarget(HttpServletRequest req) {
    Optional<HostAndPort> redirectTarget = getRedirect();
    if (redirectTarget.isPresent()) {
        HostAndPort target = redirectTarget.get();
        StringBuilder redirect = new StringBuilder().append(req.getScheme()).append("://")
                .append(target.getHost()).append(':').append(target.getPort()).append(
                        // If Jetty rewrote the path, we want to be sure to redirect to the original path
                        // rather than the rewritten path to be sure it's a route the UI code recognizes.
                        Optional.fromNullable(req.getAttribute(JettyServerModule.ORIGINAL_PATH_ATTRIBUTE_NAME))
                                .or(req.getRequestURI()));

        String queryString = req.getQueryString();
        if (queryString != null) {
            redirect.append('?').append(queryString);
        }

        return Optional.of(redirect.toString());
    } else {
        return Optional.absent();
    }
}

From source file:org.graylog2.configuration.MongoDbConfiguration.java

@Deprecated
public List<ServerAddress> getReplicaSet() {
    if (replicaSet == null || replicaSet.isEmpty()) {
        return null;
    }/* w ww  .j  a  v a  2s.  c  o  m*/

    final List<ServerAddress> replicaServers = new ArrayList<>(replicaSet.size());
    for (String host : replicaSet) {
        try {
            final HostAndPort hostAndPort = HostAndPort.fromString(host).withDefaultPort(27017);
            replicaServers.add(
                    new ServerAddress(InetAddress.getByName(hostAndPort.getHostText()), hostAndPort.getPort()));
        } catch (IllegalArgumentException e) {
            LOG.error("Malformed mongodb_replica_set configuration.", e);
            return null;
        } catch (UnknownHostException e) {
            LOG.error("Unknown host in mongodb_replica_set", e);
            return null;
        }
    }

    return replicaServers;
}

From source file:io.airlift.drift.client.address.SimpleAddressSelector.java

@Override
public Optional<SimpleAddress> selectAddress(Optional<String> addressSelectionContext,
        Set<SimpleAddress> attempted) {
    checkArgument(!addressSelectionContext.isPresent(), "addressSelectionContext should not be set");
    requireNonNull(attempted, "attempted is null");
    List<SimpleAddress> result = new ArrayList<>();
    for (HostAndPort address : addresses) {
        try {/*from ww  w  .  ja  va2 s  .c  o  m*/
            for (InetAddress ip : InetAddress.getAllByName(address.getHost())) {
                SimpleAddress simpleAddress = new SimpleAddress(
                        HostAndPort.fromParts(ip.getHostAddress(), address.getPort()));
                if (retrySameAddress || !attempted.contains(simpleAddress)) {
                    result.add(simpleAddress);
                }
            }
        } catch (UnknownHostException ignored) {
        }
    }
    if (result.isEmpty()) {
        return Optional.empty();
    }
    SimpleAddress address = result.get(ThreadLocalRandom.current().nextInt(result.size()));
    return Optional.of(address);
}

From source file:brooklyn.networking.common.subnet.PortForwarderAsyncImpl.java

@Override
public void openPortForwardingAndAdvertise(final EntityAndAttribute<Integer> source,
        final Optional<Integer> optionalPublicPort, final Protocol protocol, final Cidr accessingCidr,
        final EntityAndAttribute<String> whereToAdvertiseEndpoint) {
    Advertiser advertiser = new Advertiser() {
        @Override//from  w w  w.  j av a2s.  c om
        public void advertise(EntityAndAttribute<Integer> source, HostAndPort publicEndpoint) {
            String endpoint = publicEndpoint.getHostText() + ":" + publicEndpoint.getPort();
            whereToAdvertiseEndpoint.setValue(endpoint);
        }
    };
    doOpenPortForwardingAndAdvertise(source, optionalPublicPort, protocol, accessingCidr, advertiser);
}

From source file:com.stratio.ingestion.sink.cassandra.CassandraSink.java

@Override
public void configure(Context context) {
    contactPoints = new ArrayList<InetSocketAddress>();
    final String hosts = context.getString(CONF_HOSTS, DEFAULT_HOST);
    for (final String host : Splitter.on(',').split(hosts)) {
        try {/*from   ww  w.  j a  v a  2s.c om*/
            final HostAndPort hostAndPort = HostAndPort.fromString(host).withDefaultPort(DEFAULT_PORT);
            contactPoints.add(new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort()));
        } catch (IllegalArgumentException ex) {
            throw new ConfigurationException("Could not parse host: " + host, ex);
        }
    }

    this.username = context.getString(CONF_USERNAME);
    this.password = context.getString(CONF_PASSWORD);
    this.consistency = context.getString(CONF_CONSISTENCY_LEVEL, DEFAULT_CONSISTENCY_LEVEL);
    this.bodyColumn = context.getString(CONF_BODY_COLUMN, DEFAULT_BODY_COLUMN);

    final String tablesString = StringUtils.trimToNull(context.getString(CONF_TABLES));
    if (tablesString == null) {
        throw new ConfigurationException(String.format("%s is mandatory", CONF_TABLES));
    }
    this.tableStrings = Arrays.asList(tablesString.split(","));

    final String cqlFile = StringUtils.trimToNull(context.getString(CONF_CQL_FILE));
    if (cqlFile != null) {
        try {
            this.initCql = IOUtils.toString(new FileInputStream(cqlFile));
        } catch (IOException ex) {
            throw new ConfigurationException("Cannot read CQL file: " + cqlFile, ex);
        }
    }

    this.batchSize = context.getInteger(CONF_BATCH_SIZE, DEFAULT_BATCH_SIZE);
    this.sinkCounter = new SinkCounter(this.getName());
}

From source file:org.graylog2.logback.appender.Graylog2Plugin.java

public Graylog2Plugin(Application app) {
    final Configuration config = app.configuration();
    this.pluginEnabled = config.getBoolean("graylog2.enable.plugin", false);
    if (!this.pluginEnabled) {
        return;// w w w  .  j  av a 2s.  c  om
    }
    accessLogEnabled = config.getBoolean("graylog2.appender.send-access-log", false);
    queueCapacity = config.getInt("graylog2.appender.queue-size", 512);
    reconnectInterval = config.getMilliseconds("graylog2.appender.reconnect-interval", 500L);
    connectTimeout = config.getMilliseconds("graylog2.appender.connect-timeout", 1000L);
    isTcpNoDelay = config.getBoolean("graylog2.appender.tcp-nodelay", false);
    sendBufferSize = config.getInt("graylog2.appender.sendbuffersize", 0); // causes the socket default to be used
    try {
        canonicalHostName = config.getString("graylog2.appender.sourcehost",
                InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException e) {
        canonicalHostName = "localhost";
        log.error("Unable to resolve canonical localhost name. "
                + "Please set it manually via graylog2.appender.sourcehost or fix your lookup service, falling back to {}",
                canonicalHostName);
    }
    // TODO make this a list and dynamically accessible from the application
    final String hostString = config.getString("graylog2.appender.host", "127.0.0.1:12201");
    final String protocol = config.getString("graylog2.appender.protocol", "tcp");

    final HostAndPort hostAndPort = HostAndPort.fromString(hostString);

    final GelfTransports gelfTransport = GelfTransports.valueOf(protocol.toUpperCase());

    final GelfConfiguration gelfConfiguration = new GelfConfiguration(hostAndPort.getHostText(),
            hostAndPort.getPort()).transport(gelfTransport).reconnectDelay(reconnectInterval.intValue())
                    .queueSize(queueCapacity).connectTimeout(connectTimeout.intValue()).tcpNoDelay(isTcpNoDelay)
                    .sendBufferSize(sendBufferSize);

    this.transport = GelfTransports.create(gelfConfiguration);

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);

    gelfAppender = new GelfclientAppender(transport, getLocalHostName());
    gelfAppender.setContext(lc);
}