List of usage examples for com.google.common.net HostAndPort getPort
public int getPort()
From source file:net.myrrix.web.servlets.AbstractMyrrixServlet.java
private static String buildRedirectToPartitionURL(HttpServletRequest request, int toPartition, long unnormalizedPartitionToServe, List<List<HostAndPort>> thePartitions) { List<HostAndPort> replicas = thePartitions.get(toPartition); // Also determine (first) replica by hashing to preserve a predictable order of access // through the replicas for a given ID int chosenReplica = LangUtils.mod(RandomUtils.md5HashToLong(unnormalizedPartitionToServe), replicas.size()); HostAndPort hostPort = replicas.get(chosenReplica); StringBuilder redirectURL = new StringBuilder(); redirectURL.append(request.isSecure() ? "https" : "http").append("://"); redirectURL.append(hostPort.getHostText()).append(':').append(hostPort.getPort()); redirectURL.append(request.getRequestURI()); String query = request.getQueryString(); if (query != null) { redirectURL.append('?').append(query); }//w ww . j av a2 s .c o m return redirectURL.toString(); }
From source file:org.apache.accumulo.server.util.TServerUtils.java
public static ServerAddress createSslThreadPoolServer(HostAndPort address, TProcessor processor, long socketTimeout, SslConnectionParams sslParams) throws TTransportException { org.apache.thrift.transport.TServerSocket transport; try {/*www. j a v a 2 s . c o m*/ transport = ThriftUtil.getServerSocket(address.getPort(), (int) socketTimeout, InetAddress.getByName(address.getHostText()), sslParams); } catch (UnknownHostException e) { throw new TTransportException(e); } if (address.getPort() == 0) { address = HostAndPort.fromParts(address.getHostText(), transport.getServerSocket().getLocalPort()); } return new ServerAddress(createThreadPoolServer(transport, processor), address); }
From source file:org.voltdb.utils.Collector.java
public static boolean uploadToServer(String collectionFilePath, String host, String username, String password) throws Exception { attemptConnect(host, username, password); SSHTools ssh = new SSHTools(username, null); SFTPSession sftp = null;//from ww w .j a v a2s. c om HostAndPort hostAndPort = HostAndPort.fromString(host); if (hostAndPort.hasPort()) { sftp = ssh.getSftpSession(username, password, null, hostAndPort.getHostText(), hostAndPort.getPort(), null); } else { sftp = ssh.getSftpSession(username, password, null, host, null); } String rootpath = sftp.exec("pwd").trim(); HashMap<File, File> files = new HashMap<File, File>(); File src = new File(collectionFilePath); File dest = new File(rootpath + File.separator + new File(collectionFilePath).getName()); files.put(src, dest); try { sftp.ensureDirectoriesExistFor(files.values()); sftp.copyOverFiles(files); } finally { if (sftp != null) { sftp.terminate(); } } return true; }
From source file:zipkin.elasticsearch.ElasticsearchSpanStore.java
private static Client createClient(List<String> hosts, String clusterName) { Settings settings = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true) .build();/*from www . jav a 2 s . c om*/ TransportClient client = TransportClient.builder().settings(settings).build(); for (String host : hosts) { HostAndPort hostAndPort = HostAndPort.fromString(host); try { client.addTransportAddress(new InetSocketTransportAddress( InetAddress.getByName(hostAndPort.getHostText()), hostAndPort.getPort())); } catch (UnknownHostException e) { // Hosts may be down transiently, we should still try to connect. If all of them happen // to be down we will fail later when trying to use the client when checking the index // template. continue; } } return client; }
From source file:org.voltdb.utils.Collector.java
public static void attemptConnect(String host, String username, String password) throws Exception { SSHTools ssh = new SSHTools(username, null); try {//from w w w. j ava2 s .c om HostAndPort hostAndPort = HostAndPort.fromString(host); if (hostAndPort.hasPort()) { ssh.getSftpSession(username, password, null, hostAndPort.getHostText(), hostAndPort.getPort(), null); } else { ssh.getSftpSession(username, password, null, host, null); } } catch (SFTPException e) { String errorMsg = e.getCause().getMessage(); /* * e.getCause() is JSchException and the java exception class name only appears in message * hide java class name and extract error message */ Pattern pattern = Pattern.compile("(java.*Exception: )(.*)"); Matcher matcher = pattern.matcher(errorMsg); if (matcher.matches()) { if (errorMsg.startsWith("java.net.UnknownHostException")) { throw new Exception("Unknown host: " + matcher.group(2)); } else { throw new Exception(matcher.group(2)); } } else { if (errorMsg.equals("Auth cancel") || errorMsg.equals("Auth fail")) { // "Auth cancel" appears when username doesn't exist or password is wrong throw new Exception("Authorization rejected"); } else { throw new Exception(errorMsg.substring(0, 1).toUpperCase() + errorMsg.substring(1)); } } } catch (Exception e) { String errorMsg = e.getMessage(); throw new Exception(errorMsg.substring(0, 1).toUpperCase() + errorMsg.substring(1)); } }
From source file:org.apache.hadoop.hive.metastore.tools.Util.java
/** * Get server URI.<p>//from w ww .jav a 2 s . c om * HMS host is obtained from * <ol> * <li>Argument</li> * <li>HMS_HOST environment parameter</li> * <li>hms.host Java property</li> * <li>use 'localhost' if above fails</li> * </ol> * HMS Port is obtained from * <ol> * <li>Argument</li> * <li>host:port string</li> * <li>HMS_PORT environment variable</li> * <li>hms.port Java property</li> * <li>default port value</li> * </ol> * * @param host HMS host string. * @param portString HMS port * @return HMS URI * @throws URISyntaxException if URI is is invalid */ public static @Nullable URI getServerUri(@Nullable String host, @Nullable String portString) throws URISyntaxException { if (host == null) { host = System.getenv(ENV_SERVER); } if (host == null) { host = System.getProperty(PROP_HOST); } if (host == null) { host = DEFAULT_HOST; } host = host.trim(); if ((portString == null || portString.isEmpty() || portString.equals("0")) && !host.contains(":")) { portString = System.getenv(ENV_PORT); if (portString == null) { portString = System.getProperty(PROP_PORT); } } Integer port = Constants.HMS_DEFAULT_PORT; if (portString != null) { port = Integer.parseInt(portString); } HostAndPort hp = HostAndPort.fromString(host).withDefaultPort(port); LOG.info("Connecting to {}:{}", hp.getHostText(), hp.getPort()); return new URI(THRIFT_SCHEMA, null, hp.getHostText(), hp.getPort(), null, null, null); }
From source file:com.facebook.presto.hive.metastore.thrift.Transport.java
private static TTransport createRaw(HostAndPort address, Optional<SSLContext> sslContext, Optional<HostAndPort> socksProxy, int timeoutMillis) throws TTransportException { Proxy proxy = socksProxy/*from www .ja v a2 s .c om*/ .map(socksAddress -> new Proxy(SOCKS, InetSocketAddress.createUnresolved(socksAddress.getHost(), socksAddress.getPort()))) .orElse(Proxy.NO_PROXY); Socket socket = new Socket(proxy); try { socket.connect(new InetSocketAddress(address.getHost(), address.getPort()), timeoutMillis); socket.setSoTimeout(timeoutMillis); if (sslContext.isPresent()) { // SSL will connect to the SOCKS address when present HostAndPort sslConnectAddress = socksProxy.orElse(address); socket = sslContext.get().getSocketFactory().createSocket(socket, sslConnectAddress.getHost(), sslConnectAddress.getPort(), true); } return new TSocket(socket); } catch (Throwable t) { // something went wrong, close the socket and rethrow try { socket.close(); } catch (IOException e) { t.addSuppressed(e); } throw new TTransportException(t); } }
From source file:org.apache.accumulo.core.util.ThriftUtil.java
public static TTransport createClientTransport(HostAndPort address, int timeout, SslConnectionParams sslParams) throws TTransportException { boolean success = false; TTransport transport = null;//from www . ja v a2 s. c o m try { if (sslParams != null) { // TSSLTransportFactory handles timeout 0 -> forever natively if (sslParams.useJsse()) { transport = TSSLTransportFactory.getClientSocket(address.getHostText(), address.getPort(), timeout); } else { transport = TSSLTransportFactory.getClientSocket(address.getHostText(), address.getPort(), timeout, sslParams.getTTransportParams()); } // TSSLTransportFactory leaves transports open, so no need to open here } else if (timeout == 0) { transport = new TSocket(address.getHostText(), address.getPort()); transport.open(); } else { try { transport = TTimeoutTransport.create(address, timeout); } catch (IOException ex) { throw new TTransportException(ex); } transport.open(); } transport = ThriftUtil.transportFactory().getTransport(transport); success = true; } finally { if (!success && transport != null) { transport.close(); } } return transport; }
From source file:com.dasasian.chok.util.ZkChokUtil.java
public static ZkServer startZkServer(ZkConfiguration conf) { String server = Iterables.getOnlyElement(COMMA_SPLITTER.split(conf.getServers())); HostAndPort hostAndPort = HostAndPort.fromString(server); if (!hostAndPort.hasPort()) { throw new IllegalArgumentException("No Port Specified for ZkServer"); } else {/*from w w w . jav a2 s .c om*/ String host = hostAndPort.getHostText(); // if (!host.equals("127.0.0.1") && !host.equals("localhost")) { // throw new IllegalArgumentException("Attempting to start ZkServer remotely on " + host + " valid values are 127.0.0.1 or localhost"); // } } ZkServer zkServer = new ZkServer(conf.getDataDir(), conf.getLogDataDir(), new DefaultNameSpaceImpl(conf), hostAndPort.getPort(), conf.getTickTime()); zkServer.start(); return zkServer; }
From source file:org.apache.accumulo.server.util.TServerUtils.java
public static ServerAddress createHsHaServer(HostAndPort address, TProcessor processor, final String serverName, String threadName, final int numThreads, long timeBetweenThreadChecks, long maxMessageSize) throws TTransportException { TNonblockingServerSocket transport = new TNonblockingServerSocket( new InetSocketAddress(address.getHostText(), address.getPort())); THsHaServer.Args options = new THsHaServer.Args(transport); options.protocolFactory(ThriftUtil.protocolFactory()); options.transportFactory(ThriftUtil.transportFactory(maxMessageSize)); options.maxReadBufferBytes = maxMessageSize; options.stopTimeoutVal(5);//from www.j av a 2 s . co m /* * Create our own very special thread pool. */ final ThreadPoolExecutor pool = new SimpleThreadPool(numThreads, "ClientPool"); // periodically adjust the number of threads we need by checking how busy our threads are SimpleTimer.getInstance().schedule(new Runnable() { @Override public void run() { if (pool.getCorePoolSize() <= pool.getActiveCount()) { int larger = pool.getCorePoolSize() + Math.min(pool.getQueue().size(), 2); log.info("Increasing server thread pool size on " + serverName + " to " + larger); pool.setMaximumPoolSize(larger); pool.setCorePoolSize(larger); } else { if (pool.getCorePoolSize() > pool.getActiveCount() + 3) { int smaller = Math.max(numThreads, pool.getCorePoolSize() - 1); if (smaller != pool.getCorePoolSize()) { // there is a race condition here... the active count could be higher by the time // we decrease the core pool size... so the active count could end up higher than // the core pool size, in which case everything will be queued... the increase case // should handle this and prevent deadlock log.info("Decreasing server thread pool size on " + serverName + " to " + smaller); pool.setCorePoolSize(smaller); } } } } }, timeBetweenThreadChecks, timeBetweenThreadChecks); options.executorService(pool); options.processorFactory(new TProcessorFactory(processor)); if (address.getPort() == 0) { address = HostAndPort.fromParts(address.getHostText(), transport.getPort()); } return new ServerAddress(new THsHaServer(options), address); }