List of usage examples for com.google.common.net HostAndPort getHostText
public String getHostText()
From source file:org.apache.accumulo.server.rpc.TServerUtils.java
/** * Creates a TTheadPoolServer for normal unsecure operation. Useful for comparing performance against SSL or SASL transports. * * @param address/*from w w w . ja va 2 s . c o m*/ * Address to bind to * @param processor * TProcessor for the server * @param maxMessageSize * Maximum size of a Thrift message allowed * @return A configured TThreadPoolServer and its bound address information */ public static ServerAddress createBlockingServer(HostAndPort address, TProcessor processor, TProtocolFactory protocolFactory, long maxMessageSize, String serverName, int numThreads, int numSimpleTimerThreads, long timeBetweenThreadChecks) throws TTransportException { TServerSocket transport = new TServerSocket(address.getPort()); ThreadPoolExecutor pool = createSelfResizingThreadPool(serverName, numThreads, numSimpleTimerThreads, timeBetweenThreadChecks); TThreadPoolServer server = createTThreadPoolServer(transport, processor, ThriftUtil.transportFactory(maxMessageSize), protocolFactory, pool); if (address.getPort() == 0) { address = HostAndPort.fromParts(address.getHostText(), transport.getServerSocket().getLocalPort()); } return new ServerAddress(server, address); }
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. j a v a 2s. 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:ratpack.server.internal.DefaultPublicAddress.java
public URI getAddress(Context context) { return publicAddress.orElseGet(() -> { String scheme;// w w w .jav a2 s. co m String host; int port; HostAndPort forwardedHostData = getForwardedHostData(context); if (forwardedHostData != null) { scheme = determineScheme(context, this.scheme); host = forwardedHostData.getHostText(); port = forwardedHostData.getPortOrDefault(-1); } else { URI absoluteRequestURI = getAbsoluteRequestUri(context); if (absoluteRequestURI != null) { scheme = determineScheme(context, absoluteRequestURI.getScheme()); host = absoluteRequestURI.getHost(); port = absoluteRequestURI.getPort(); } else { scheme = determineScheme(context, this.scheme); HostAndPort hostData = getHostData(context); if (hostData != null) { host = hostData.getHostText(); port = hostData.getPortOrDefault(-1); } else { HostAndPort localAddress = context.getRequest().getLocalAddress(); host = localAddress.getHostText(); port = ProtocolUtil.isDefaultPortForScheme(localAddress.getPort(), this.scheme) ? -1 : localAddress.getPort(); } } } try { return new URI(scheme, null, host, port, null, null, null); } catch (URISyntaxException ex) { throw Exceptions.uncheck(ex); } }); }
From source file:org.apache.kudu.client.ConnectionCache.java
TabletClient newClient(String uuid, HostAndPort hostPort) { InetAddress inetAddress = NetUtil.getInetAddress(hostPort.getHostText()); if (inetAddress == null) { // TODO(todd): should we log the resolution failure? throw an exception? return null; }/*from w ww . ja v a2 s . c o m*/ ServerInfo serverInfo = new ServerInfo(uuid, hostPort, inetAddress); return newClient(serverInfo); }
From source file:org.grycap.gpf4med.reflect.AsyncHandler.java
@Override protected Object handleInvocation(final Object proxy, final Method method, final Object[] args) throws Throwable { final Group group = groupFromArgs(args, fromDefaultGroup()); if ("create".equals(method.getName())) { checkArgument(group != null, "Uninitialized group"); // check and create group final Iterable<HostAndPort> servers = CloudService.INSTANCE.list(group.getGroup()); checkState(servers == null || !servers.iterator().hasNext(), "A previous group exists"); final int numServers = numServers(fromDefaults(), reportsCount(args), type); CloudService.INSTANCE.addServers(group.getGroup(), numServers); }/*ww w . j av a 2 s . c o m*/ final Iterable<HostAndPort> servers = CloudService.INSTANCE.list(group.getGroup()); checkState(servers != null, "No servers were found in the group"); // execute the operation on the servers final List<ListenableFuture<Object>> futures = synchronizedList(new ArrayList<ListenableFuture<Object>>()); for (final Iterator<HostAndPort> it = servers.iterator(); it.hasNext();) { final ListenableFuture<Object> future = executorService.submit(new Callable<Object>() { @Override public Object call() throws Exception { final HostAndPort hostAndPort = it.next(); final String baseURL = "http://" + hostAndPort.getHostText() + ":" + hostAndPort.getPortOrDefault(80); final Path path = type.getAnnotation(Path.class); final T underlying = newResourceProxyClient(baseURL, path.value(), type); return method.invoke(underlying, args); } }); futures.add(future); } // handle results final ListenableFuture<List<Object>> resultsFuture = successfulAsList(futures); List<Object> results = null; try { results = resultsFuture.get(MILLISECONDS.convert(EXEC_TIMEOUT_MINUTES, MINUTES), MILLISECONDS); } catch (InterruptedException | TimeoutException e) { LOGGER.warn("Failed to execute method " + method.getName() + " on group: " + group, e); } catch (ExecutionException e) { throw e.getCause(); } if (method.getReturnType() == void.class) { return null; } return mergeResults(results); }
From source file:org.rakam.http.WebServiceModule.java
@Override protected void configure() { Info info = new Info().title("Rakam API Documentation").version(ServiceStarter.RAKAM_VERSION) .description("An analytics platform API that lets you create your own analytics services.") .contact(new Contact().email("contact@rakam.io")).license(new License().name("Apache License 2.0") .url("http://www.apache.org/licenses/LICENSE-2.0.html")); Swagger swagger = new Swagger().info(info).host("app.rakam.io").basePath("/") .tags(ImmutableList.copyOf(tags)) .securityDefinition("write_key", new ApiKeyAuthDefinition().in(In.HEADER).name("write_key")) .securityDefinition("read_key", new ApiKeyAuthDefinition().in(In.HEADER).name("read_key")) .securityDefinition("master_key", new ApiKeyAuthDefinition().in(In.HEADER).name("master_key")); EventLoopGroup eventExecutors;//from w ww . j a v a 2 s.c o m if (Epoll.isAvailable()) { eventExecutors = new EpollEventLoopGroup(); } else { eventExecutors = new NioEventLoopGroup(); } HttpServerBuilder httpServer = new HttpServerBuilder().setHttpServices(httpServices) .setWebsockerServices(webSocketServices).setSwagger(swagger) .setMaximumBody(Runtime.getRuntime().maxMemory() / 10).setEventLoopGroup(eventExecutors) .setSwaggerOperationProcessor((method, operation) -> { ApiOperation annotation = method.getAnnotation(ApiOperation.class); if (annotation != null && annotation.authorizations() != null && annotation.authorizations().length > 0) { String value = annotation.authorizations()[0].value(); if (value != null && !value.isEmpty()) { operation.response(FORBIDDEN.code(), new Response() .schema(new RefProperty("ErrorMessage")).description(value + " is invalid")); } } }).setMapper(JsonHelper.getMapper()).setDebugMode(config.getDebug()) .setProxyProtocol(config.getProxyProtocol()).setExceptionHandler((request, ex) -> { if (ex instanceof RakamException) { LogUtil.logException(request, (RakamException) ex); } if (!(ex instanceof HttpRequestException)) { LogUtil.logException(request, ex); } }).setOverridenMappings(ImmutableMap.of(GenericRecord.class, PrimitiveType.OBJECT)) .addPostProcessor(response -> response.headers().set(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"), method -> method.isAnnotationPresent(AllowCookie.class)); requestPreProcessorItems.forEach(i -> httpServer.addJsonPreprocessor(i.processor, i.predicate)); ImmutableMap.Builder<String, IRequestParameterFactory> builder = ImmutableMap .<String, IRequestParameterFactory>builder(); for (CustomParameter customParameter : customParameters) { builder.put(customParameter.parameterName, customParameter.factory); } httpServer.setCustomRequestParameters(builder.build()); HttpServer build = httpServer.build(); if (requestHandler != null) { build.setNotFoundHandler(requestHandler); } HostAndPort address = config.getAddress(); try { build.bind(address.getHostText(), address.getPort()); } catch (InterruptedException e) { addError(e); return; } binder().bind(HttpServer.class).toInstance(build); }
From source file:brooklyn.entity.chef.KnifeConvergeTaskFactory.java
/** construct the knife command, based on the settings on other methods * (called when instantiating the script, after all parameters sent) *//*from w w w . j a v a 2 s. c om*/ protected List<String> initialKnifeParameters() { // runs inside the task so can detect entity/machine at runtime MutableList<String> result = new MutableList<String>(); SshMachineLocation machine = EffectorTasks.findSshMachine(); result.add("bootstrap"); result.addAll(extraBootstrapParameters); HostAndPort hostAndPort = machine.getSshHostAndPort(); result.add(wrapBash(hostAndPort.getHostText())); Integer whichPort = knifeWhichPort(hostAndPort); if (whichPort != null) result.add("-p " + whichPort); result.add("-x " + wrapBash(checkNotNull(machine.getUser(), "user"))); File keyfile = ChefServerTasks.extractKeyFile(machine); if (keyfile != null) result.add("-i " + keyfile.getPath()); else result.add( "-P " + checkNotNull(machine.findPassword(), "No password or private key data for " + machine)); if (sudo != Boolean.FALSE) result.add("--sudo"); if (!Strings.isNullOrEmpty(nodeName)) { result.add("--node-name"); result.add(nodeName); } result.add("-r " + wrapBash(runList.apply(entity()))); if (!knifeAttributes.isEmpty()) result.add("-j " + wrapBash(new GsonBuilder().create().toJson(knifeAttributes))); return result; }
From source file:com.pingcap.tikv.PDClient.java
private ManagedChannel getManagedChannel(HostAndPort url) { return ManagedChannelBuilder.forAddress(url.getHostText(), url.getPort()).usePlaintext(true).build(); }
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 w ww. j a va2s . co m throw new IllegalStateException("HTTP and HTTPS protocols not enabled for " + entity + "; enabled protocols are " + getEnabledProtocols()); } }
From source file:org.apache.brooklyn.entity.chef.KnifeConvergeTaskFactory.java
/** construct the knife command, based on the settings on other methods * (called when instantiating the script, after all parameters sent) *//*w w w . ja v a 2 s.co m*/ protected List<String> initialKnifeParameters() { // runs inside the task so can detect entity/machine at runtime MutableList<String> result = new MutableList<String>(); SshMachineLocation machine = EffectorTasks.findSshMachine(); result.add("bootstrap"); result.addAll(extraBootstrapParameters); HostAndPort hostAndPort = machine.getSshHostAndPort(); result.add(wrapBash(hostAndPort.getHostText())); Integer whichPort = knifeWhichPort(hostAndPort); if (whichPort != null) result.add("-p " + whichPort); result.add("-x " + wrapBash(checkNotNull(machine.getUser(), "user"))); File keyfile = ChefServerTasks.extractKeyFile(machine); if (keyfile != null) result.add("-i " + keyfile.getPath()); else result.add( "-P " + checkNotNull(machine.findPassword(), "No password or private key data for " + machine)); result.add("--no-host-key-verify"); if (sudo != Boolean.FALSE) result.add("--sudo"); if (!Strings.isNullOrEmpty(nodeName)) { result.add("--node-name"); result.add(nodeName); } result.add("-r " + wrapBash(runList.apply(entity()))); if (!knifeAttributes.isEmpty()) result.add("-j " + wrapBash(new GsonBuilder().create().toJson(knifeAttributes))); return result; }