List of usage examples for com.google.common.net HostAndPort fromString
public static HostAndPort fromString(String hostPortString)
From source file:com.netflix.simianarmy.client.chef.ChefClient.java
@Override /**//from w ww . j a v a 2s .c o m * connect to the given instance with the given credentials */ public SshClient connectSsh(String instanceId, LoginCredentials credentials) { for (Node node : context.getChefService().listNodes()) { if (node.getName().equals(instanceId)) { HostAndPort socket = HostAndPort.fromString(node.getName()).withDefaultPort(22); //Use JschSshClient directly, had some problems when trying to go through jclouds SshClient ssh = new JschSshClient(new GuiceProxyConfig(), BackoffLimitedRetryHandler.INSTANCE, socket, credentials, 3000); LOGGER.info(String.format("Opening ssh connection to %s (%s)", instanceId, socket.toString())); ssh.connect(); return ssh; } } return null; }
From source file:alluxio.wire.FileBlockInfo.java
/** * @return thrift representation of the file block information *//*from w w w . ja v a2 s.co m*/ protected alluxio.thrift.FileBlockInfo toThrift() { List<alluxio.thrift.WorkerNetAddress> ufsLocations = new ArrayList<>(); for (String ufsLocation : mUfsLocations) { HostAndPort address = HostAndPort.fromString(ufsLocation); ufsLocations.add(new alluxio.thrift.WorkerNetAddress().setHost(address.getHostText()) .setDataPort(address.getPortOrDefault(-1))); } return new alluxio.thrift.FileBlockInfo(mBlockInfo.toThrift(), mOffset, ufsLocations, mUfsLocations); }
From source file:com.bouncestorage.chaoshttpproxy.ChaosHttpProxyHandler.java
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse servletResponse) throws IOException { baseRequest.setHandled(true);//from w ww . j a v a2 s .c o m // CONNECT is not supported pending implementation of MITM HTTPS if (request.getMethod().equals("CONNECT")) { logger.debug("CONNECT is not supported"); servletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } Failure failure = supplier.get(); logger.debug("request: {}", request); logger.debug("Failure: {}", failure); try (InputStream is = request.getInputStream(); OutputStream os = servletResponse.getOutputStream()) { HostAndPort hostAndPort = HostAndPort.fromString(request.getHeader(HttpHeaders.HOST)); String queryString = request.getQueryString(); URI uri; try { uri = new URI(request.getScheme(), /*userInfo=*/ null, hostAndPort.getHostText(), hostAndPort.hasPort() ? hostAndPort.getPort() : 80, request.getRequestURI(), queryString, /*fragment=*/ null); } catch (URISyntaxException use) { throw new IOException(use); } logger.debug("uri: {}", uri); URI redirectedUri = redirects.get(uri); if (redirectedUri != null) { // TODO: parameters uri = redirectedUri; logger.debug("redirected uri: {}", uri); } switch (failure) { case HTTP_301: case HTTP_302: case HTTP_303: case HTTP_307: case HTTP_308: servletResponse.setStatus(failure.getResponseCode()); URI redirectUri; try { redirectUri = new URI(request.getScheme(), /*userInfo=*/ null, hostAndPort.getHostText(), hostAndPort.hasPort() ? hostAndPort.getPort() : 80, "/" + UUID.randomUUID().toString(), /*query=*/ null, /*fragment=*/ null); } catch (URISyntaxException use) { throw new IOException(use); } redirects.put(redirectUri, uri); servletResponse.addHeader(HttpHeaders.LOCATION, redirectUri.toString()); return; case HTTP_408: case HTTP_500: case HTTP_503: case HTTP_504: servletResponse.setStatus(failure.getResponseCode()); return; case TIMEOUT: Uninterruptibles.sleepUninterruptibly(Long.MAX_VALUE, TimeUnit.DAYS); return; default: break; } InputStreamResponseListener listener = new InputStreamResponseListener(); InputStream iss = failure == Failure.PARTIAL_REQUEST ? // TODO: random limit ByteStreams.limit(is, 1024) : is; org.eclipse.jetty.client.api.Request clientRequest = client.newRequest(uri.toString()) .method(request.getMethod()); long userContentLength = -1; for (String headerName : Collections.list(request.getHeaderNames())) { if (headerName.equalsIgnoreCase(HttpHeaders.EXPECT) || headerName.equalsIgnoreCase("Proxy-Connection")) { continue; } String headerValue = request.getHeader(headerName); logger.trace("{}: {}", headerName, headerValue); if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_MD5) && failure == Failure.CORRUPT_REQUEST_CONTENT_MD5) { headerValue = headerValue.toUpperCase(); } if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { userContentLength = Long.parseLong(headerValue); } clientRequest.header(headerName, headerValue); } // Work around Jetty bug that strips Content-Length // https://bugs.eclipse.org/bugs/show_bug.cgi?id=475613. final long length = userContentLength; clientRequest.content(new InputStreamContentProvider(iss) { @Override public long getLength() { return length != -1 ? length : super.getLength(); } }); clientRequest.send(listener); if (failure == Failure.PARTIAL_REQUEST) { return; } Response response; try { response = listener.get(Long.MAX_VALUE, TimeUnit.SECONDS); } catch (ExecutionException | InterruptedException | TimeoutException e) { throw new IOException(e); } int status = response.getStatus(); logger.trace("status: {}", status); servletResponse.setStatus(status); List<HttpField> headers = Lists.newArrayList(response.getHeaders()); if (failure == Failure.REORDER_HEADERS) { Collections.shuffle(headers); } for (HttpField field : headers) { String header = field.getName(); String value = field.getValue(); logger.trace("header: {}: {}", header, value); switch (failure) { case CHANGE_HEADER_CASE: // TODO: randomly change between upper- and lower-case header = header.toUpperCase(); break; case CORRUPT_RESPONSE_CONTENT_MD5: if (header.equals(HttpHeaders.CONTENT_MD5)) { value = BaseEncoding.base64().encode(new byte[Hashing.md5().bits() / 8]); } break; default: break; } servletResponse.addHeader(header, value); } try (InputStream responseContent = listener.getInputStream()) { switch (failure) { case PARTIAL_RESPONSE: byte[] array = new byte[1024]; int count = responseContent.read(array); if (count != -1) { // TODO: randomly read n - 1 bytes os.write(array, 0, count / 2); os.flush(); } return; case SLOW_RESPONSE: for (int i = 0; i < 10; ++i) { int ch = responseContent.read(); if (ch == -1) { break; } os.write(ch); os.flush(); Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); } break; default: break; } ByteStreams.copy(responseContent, os); } } }
From source file:org.apache.accumulo.core.client.impl.ReplicationClient.java
public static ReplicationCoordinator.Client getCoordinatorConnection(ClientContext context) { Instance instance = context.getInstance(); List<String> locations = instance.getMasterLocations(); if (locations.size() == 0) { log.debug("No masters for replication to instance {}", instance.getInstanceName()); return null; }/*from w ww . j a v a2 s . co m*/ // This is the master thrift service, we just want the hostname, not the port String masterThriftService = locations.get(0); if (masterThriftService.endsWith(":0")) { log.warn("Master found for {} did not have real location {}", instance.getInstanceName(), masterThriftService); return null; } String zkPath = ZooUtil.getRoot(instance) + Constants.ZMASTER_REPLICATION_COORDINATOR_ADDR; String replCoordinatorAddr; log.debug("Using ZooKeeper quorum at {} with path {} to find peer Master information", instance.getZooKeepers(), zkPath); // Get the coordinator port for the master we're trying to connect to try { ZooReader reader = new ZooReader(instance.getZooKeepers(), instance.getZooKeepersSessionTimeOut()); replCoordinatorAddr = new String(reader.getData(zkPath, null), UTF_8); } catch (KeeperException | InterruptedException e) { log.error("Could not fetch remote coordinator port", e); return null; } // Throw the hostname and port through HostAndPort to get some normalization HostAndPort coordinatorAddr = HostAndPort.fromString(replCoordinatorAddr); log.debug("Connecting to master at {}", coordinatorAddr); try { // Master requests can take a long time: don't ever time out ReplicationCoordinator.Client client = ThriftUtil .getClientNoTimeout(new ReplicationCoordinator.Client.Factory(), coordinatorAddr, context); return client; } catch (TTransportException tte) { log.debug("Failed to connect to master coordinator service ({})", coordinatorAddr, tte); return null; } }
From source file:ratpack.server.internal.InferringPublicAddress.java
private HostAndPort getForwardedHostData(Request request) { Headers headers = request.getHeaders(); String forwardedHostHeader = Strings.emptyToNull(headers.get(X_FORWARDED_HOST.toString())); String hostPortString = forwardedHostHeader != null ? Iterables.getFirst(FORWARDED_HOST_SPLITTER.split(forwardedHostHeader), null) : null;//from ww w . j a v a 2s.c o m return hostPortString != null ? HostAndPort.fromString(hostPortString) : null; }
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 {// w w w .j a va2 s.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:com.torodb.Config.java
@Nullable public HostAndPort getSyncSource() { if (syncSourceAddress == null) { return null; } return HostAndPort.fromString(syncSourceAddress); }
From source file:ezbake.ezdiscovery.ServiceDiscoveryClient.java
/** * Register a service end point for service discovery * *@param appName the name of the application that we are registering the service for *@param serviceName the name of the service that we are registering *@param point the host:port number of a service end point * *@throws Exception for any zookeeper errors *//* w ww .j av a2 s . c o m*/ @SuppressWarnings("PMD.EmptyCatchBlock") @Override public void registerEndpoint(final String appName, final String serviceName, final String point) throws Exception { HostAndPort.fromString(point); // use this to validate that we have a somewhat valid host and port string final String path = ServiceDiscoveryClient.makeZKPath(appName, serviceName, ENDPOINTS_ZK_PATH, point); try { zkClient.delete().forPath(path); } catch (KeeperException.NoNodeException e) { // Do nothing here, since if it doesn't exists its all good, as we are going to create it } zkClient.create().creatingParentsIfNeeded().forPath(path); }
From source file:org.apache.accumulo.core.client.impl.ThriftScanner.java
public static boolean getBatchFromServer(ClientContext context, Range range, KeyExtent extent, String server, SortedMap<Key, Value> results, SortedSet<Column> fetchedColumns, List<IterInfo> serverSideIteratorList, Map<String, Map<String, String>> serverSideIteratorOptions, int size, Authorizations authorizations, boolean retry, long batchTimeOut, String classLoaderContext) throws AccumuloException, AccumuloSecurityException, NotServingTabletException { if (server == null) throw new AccumuloException(new IOException()); final HostAndPort parsedServer = HostAndPort.fromString(server); try {/*from w w w . jav a 2 s .co m*/ TInfo tinfo = Tracer.traceInfo(); TabletClientService.Client client = ThriftUtil.getTServerClient(parsedServer, context); try { // not reading whole rows (or stopping on row boundries) so there is no need to enable isolation below ScanState scanState = new ScanState(context, extent.getTableId(), authorizations, range, fetchedColumns, size, serverSideIteratorList, serverSideIteratorOptions, false, Constants.SCANNER_DEFAULT_READAHEAD_THRESHOLD, null, batchTimeOut, classLoaderContext); TabletType ttype = TabletType.type(extent); boolean waitForWrites = !serversWaitedForWrites.get(ttype).contains(server); InitialScan isr = client.startScan(tinfo, scanState.context.rpcCreds(), extent.toThrift(), scanState.range.toThrift(), Translator.translate(scanState.columns, Translators.CT), scanState.size, scanState.serverSideIteratorList, scanState.serverSideIteratorOptions, scanState.authorizations.getAuthorizationsBB(), waitForWrites, scanState.isolated, scanState.readaheadThreshold, null, scanState.batchTimeOut, classLoaderContext); if (waitForWrites) serversWaitedForWrites.get(ttype).add(server); Key.decompress(isr.result.results); for (TKeyValue kv : isr.result.results) results.put(new Key(kv.key), new Value(kv.value)); client.closeScan(tinfo, isr.scanID); return isr.result.more; } finally { ThriftUtil.returnClient(client); } } catch (TApplicationException tae) { throw new AccumuloServerException(server, tae); } catch (TooManyFilesException e) { log.debug("Tablet ({}) has too many files {} : {}", extent, server, e.getMessage()); } catch (ThriftSecurityException e) { log.warn("Security Violation in scan request to {}: {}", server, e.getMessage()); throw new AccumuloSecurityException(e.user, e.code, e); } catch (TException e) { log.debug("Error getting transport to {}: {}", server, e.getMessage()); } throw new AccumuloException("getBatchFromServer: failed"); }
From source file:ratpack.server.internal.InferringPublicAddress.java
private HostAndPort getHostData(Request request) { Headers headers = request.getHeaders(); String hostPortString = Strings.emptyToNull(headers.get(HOST.toString())); return hostPortString != null ? HostAndPort.fromString(hostPortString) : null; }