use of java.net.http.HttpClient in project jena by apache.
the class RemoteEndpointDriver method connect.
@Override
protected JenaConnection connect(Properties props, int compatibilityLevel) throws SQLException {
String queryEndpoint = props.getProperty(PARAM_QUERY_ENDPOINT);
String updateEndpoint = props.getProperty(PARAM_UPDATE_ENDPOINT);
// Validate at least one endpoint present
if (queryEndpoint == null && updateEndpoint == null)
throw new SQLException("At least one of the " + PARAM_QUERY_ENDPOINT + " or " + PARAM_UPDATE_ENDPOINT + " connection parameters must be specified to make a remote connection");
// Gather dataset related parameters
List<String> defaultGraphs = this.getValues(props, PARAM_DEFAULT_GRAPH_URI);
List<String> namedGraphs = this.getValues(props, PARAM_NAMED_GRAPH_URI);
List<String> usingGraphs = this.getValues(props, PARAM_USING_GRAPH_URI);
List<String> usingNamedGraphs = this.getValues(props, PARAM_USING_NAMED_GRAPH_URI);
// Authentication settings
HttpClient client = this.configureClient(props);
// Result Types
String selectResultsType = props.getProperty(PARAM_SELECT_RESULTS_TYPE, null);
String modelResultsType = props.getProperty(PARAM_MODEL_RESULTS_TYPE, null);
// Create connection
return openConnection(queryEndpoint, updateEndpoint, defaultGraphs, namedGraphs, usingGraphs, usingNamedGraphs, client, JenaConnection.DEFAULT_HOLDABILITY, compatibilityLevel, selectResultsType, modelResultsType);
}
use of java.net.http.HttpClient in project pravega by pravega.
the class ControllerPrometheusTest method testPrometheusMetrics.
@Test
public void testPrometheusMetrics() throws Exception {
MetricsProvider.initialize(MetricsConfig.builder().with(MetricsConfig.ENABLE_STATISTICS, true).with(MetricsConfig.ENABLE_PROMETHEUS, true).with(MetricsConfig.METRICS_PREFIX, "promtestcontroller").build());
@Cleanup StatsProvider statsProvider = MetricsProvider.getMetricsProvider();
statsProvider.start();
@Cleanup ControllerServiceStarter starter = new ControllerServiceStarter(createControllerServiceConfig(), storeClient, null);
starter.startAsync();
starter.awaitRunning();
Counter c = statsProvider.createStatsLogger("promtest").createCounter("promtestcounter");
c.add(1);
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:" + this.restPort + "/prometheus")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(response.body().lines().anyMatch(x -> Pattern.matches("promtestcounter.*1\\.0", x)));
starter.stopAsync();
starter.awaitTerminated();
}
use of java.net.http.HttpClient in project pravega by pravega.
the class PrometheusTest method testPrometheusMetrics.
@Test
public void testPrometheusMetrics() throws Exception {
@Cleanup StatsProvider statsProvider = MetricsProvider.getMetricsProvider();
statsProvider.start();
Counter c = statsProvider.createStatsLogger("promtest").createCounter("promtestcounter");
c.add(1);
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:" + this.restPort + "/prometheus")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(response.body().lines().anyMatch(x -> Pattern.matches("promtestcounter.*1\\.0", x)));
}
use of java.net.http.HttpClient in project pravega by pravega.
the class PrometheusResourceTest method testScrape.
@Test
public void testScrape() throws Exception {
MetricsConfig appConfig = MetricsConfig.builder().with(MetricsConfig.ENABLE_STATISTICS, true).with(MetricsConfig.ENABLE_PROMETHEUS, true).build();
@Cleanup CompositeMeterRegistry localRegistry = new CompositeMeterRegistry();
@Cleanup StatsProvider statsProvider = new StatsProviderImpl(appConfig, localRegistry);
statsProvider.start();
for (MeterRegistry registry : localRegistry.getRegistries()) {
assertTrue(registry instanceof PrometheusMeterRegistry);
}
assertTrue(statsProvider.prometheusResource().isPresent());
ResourceConfig rc = ResourceConfig.forApplication(new PrometheusApplication(statsProvider));
URI baseUri = UriBuilder.fromUri("http://localhost/").port(TestUtils.getAvailableListenPort()).build();
@Cleanup("shutdown") HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri, rc);
Counter c = statsProvider.createStatsLogger("promtest").createCounter("promtestcounter");
c.add(1);
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(baseUri + "prometheus")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(response.body().lines().anyMatch(x -> Pattern.matches("promtestcounter.*1\\.0", x)));
server.shutdown();
}
use of java.net.http.HttpClient in project redkale by redkale.
the class Application method init.
public void init() throws Exception {
System.setProperty("redkale.net.transport.poolmaxconns", "100");
System.setProperty("redkale.net.transport.pinginterval", "30");
System.setProperty("redkale.net.transport.checkinterval", "30");
System.setProperty("redkale.convert.tiny", "true");
System.setProperty("redkale.convert.pool.size", "128");
System.setProperty("redkale.convert.writer.buffer.defsize", "4096");
final String confDir = this.confPath.toString();
final String homepath = this.home.getCanonicalPath();
if ("file".equals(this.confPath.getScheme())) {
File persist = new File(new File(confPath), "persistence.xml");
if (persist.isFile())
System.setProperty(DataSources.DATASOURCE_CONFPATH, persist.getCanonicalPath());
} else {
System.setProperty(DataSources.DATASOURCE_CONFPATH, confDir + (confDir.endsWith("/") ? "" : "/") + "persistence.xml");
}
// String pidstr = "";
// try { //JDK 9+
// Class phclass = Thread.currentThread().getContextClassLoader().loadClass("java.lang.ProcessHandle");
// Object phobj = phclass.getMethod("current").invoke(null);
// Object pid = phclass.getMethod("pid").invoke(phobj);
// pidstr = "APP_PID = " + pid + "\r\n";
// } catch (Throwable t) {
// }
logger.log(Level.INFO, "APP_OSNAME = " + System.getProperty("os.name") + " " + System.getProperty("os.version") + " " + System.getProperty("os.arch") + "\r\n" + "APP_JAVA = " + System.getProperty("java.runtime.name", System.getProperty("org.graalvm.nativeimage.kind") != null ? "Nativeimage" : "") + " " + System.getProperty("java.runtime.version", System.getProperty("java.vendor.version", System.getProperty("java.vm.version"))) + // graalvm.nativeimage 模式下无 java.runtime.xxx 属性
"\r\n" + "APP_PID = " + ProcessHandle.current().pid() + "\r\n" + RESNAME_APP_NODEID + " = " + this.nodeid + "\r\n" + "APP_LOADER = " + this.classLoader.getClass().getSimpleName() + "\r\n" + RESNAME_APP_ADDR + " = " + this.localAddress.getHostString() + ":" + this.localAddress.getPort() + "\r\n" + RESNAME_APP_HOME + " = " + homepath + "\r\n" + RESNAME_APP_CONF + " = " + confDir.substring(confDir.indexOf('!') + 1));
if (!compileMode && !(classLoader instanceof RedkaleClassLoader.RedkaleCacheClassLoader)) {
String lib = config.getValue("lib", "${APP_HOME}/libs/*").trim().replace("${APP_HOME}", homepath);
lib = lib.isEmpty() ? confDir : (lib + ";" + confDir);
Server.loadLib(classLoader, logger, lib);
}
// ------------------------------------------------------------------------
final AnyValue resources = config.getAnyValue("resources");
if (resources != null) {
resourceFactory.register(RESNAME_APP_GRES, AnyValue.class, resources);
final AnyValue properties = resources.getAnyValue("properties");
if (properties != null) {
String dfloads = properties.getValue("load");
if (dfloads != null) {
for (String dfload : dfloads.split(";")) {
if (dfload.trim().isEmpty())
continue;
final URI df = RedkaleClassLoader.getConfResourceAsURI(configFromCache ? null : confDir, dfload.trim());
if (df != null && (!"file".equals(df.getScheme()) || df.toString().contains("!") || new File(df).isFile())) {
Properties ps = new Properties();
try {
InputStream in = df.toURL().openStream();
ps.load(in);
in.close();
ps.forEach((x, y) -> resourceFactory.register("property." + x, y.toString().replace("${APP_HOME}", homepath)));
} catch (Exception e) {
logger.log(Level.WARNING, "load properties(" + dfload + ") error", e);
}
}
}
}
for (AnyValue prop : properties.getAnyValues("property")) {
String name = prop.getValue("name");
String value = prop.getValue("value");
if (name == null || value == null)
continue;
value = value.replace("${APP_HOME}", homepath);
if (name.startsWith("system.property.")) {
System.setProperty(name.substring("system.property.".length()), value);
} else if (name.startsWith("mimetype.property.")) {
MimeType.add(name.substring("mimetype.property.".length()), value);
} else if (name.startsWith("property.")) {
resourceFactory.register(name, value);
} else {
resourceFactory.register("property." + name, value);
}
}
}
}
this.resourceFactory.register(BsonFactory.root());
this.resourceFactory.register(JsonFactory.root());
this.resourceFactory.register(BsonFactory.root().getConvert());
this.resourceFactory.register(JsonFactory.root().getConvert());
this.resourceFactory.register("bsonconvert", Convert.class, BsonFactory.root().getConvert());
this.resourceFactory.register("jsonconvert", Convert.class, JsonFactory.root().getConvert());
// 只有WatchService才能加载Application、WatchFactory
final Application application = this;
this.resourceFactory.register(new ResourceFactory.ResourceLoader() {
@Override
public void load(ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) {
try {
Resource res = field.getAnnotation(Resource.class);
if (res == null)
return;
// 远程模式不得注入
if (src instanceof Service && Sncp.isRemote((Service) src))
return;
Class type = field.getType();
if (type == Application.class) {
field.set(src, application);
} else if (type == ResourceFactory.class) {
boolean serv = RESNAME_SERVER_RESFACTORY.equals(res.name()) || res.name().equalsIgnoreCase("server");
field.set(src, serv ? rf : (res.name().isEmpty() ? application.resourceFactory : null));
} else if (type == TransportFactory.class) {
field.set(src, application.sncpTransportFactory);
} else if (type == NodeSncpServer.class) {
NodeServer server = null;
for (NodeServer ns : application.getNodeServers()) {
if (ns.getClass() != NodeSncpServer.class)
continue;
if (res.name().equals(ns.server.getName())) {
server = ns;
break;
}
}
field.set(src, server);
} else if (type == NodeHttpServer.class) {
NodeServer server = null;
for (NodeServer ns : application.getNodeServers()) {
if (ns.getClass() != NodeHttpServer.class)
continue;
if (res.name().equals(ns.server.getName())) {
server = ns;
break;
}
}
field.set(src, server);
} else if (type == NodeWatchServer.class) {
NodeServer server = null;
for (NodeServer ns : application.getNodeServers()) {
if (ns.getClass() != NodeWatchServer.class)
continue;
if (res.name().equals(ns.server.getName())) {
server = ns;
break;
}
}
field.set(src, server);
}
// if (type == WatchFactory.class) {
// field.set(src, application.watchFactory);
// }
} catch (Exception e) {
logger.log(Level.SEVERE, "Resource inject error", e);
}
}
@Override
public boolean autoNone() {
return false;
}
}, Application.class, ResourceFactory.class, TransportFactory.class, NodeSncpServer.class, NodeHttpServer.class, NodeWatchServer.class);
// ------------------------------------- 注册 java.net.http.HttpClient --------------------------------------------------------
resourceFactory.register((ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) -> {
try {
if (field.getAnnotation(Resource.class) == null)
return;
java.net.http.HttpClient.Builder builder = java.net.http.HttpClient.newBuilder();
if (resourceName.endsWith(".1.1")) {
builder.version(HttpClient.Version.HTTP_1_1);
} else if (resourceName.endsWith(".2")) {
builder.version(HttpClient.Version.HTTP_2);
}
java.net.http.HttpClient httpClient = builder.build();
field.set(src, httpClient);
// 给其可能包含@Resource的字段赋值;
rf.inject(httpClient, null);
rf.register(resourceName, java.net.http.HttpClient.class, httpClient);
} catch (Exception e) {
logger.log(Level.SEVERE, "[" + Thread.currentThread().getName() + "] java.net.http.HttpClient inject error", e);
}
}, java.net.http.HttpClient.class);
// ------------------------------------- 注册 HttpSimpleClient --------------------------------------------------------
resourceFactory.register((ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) -> {
try {
if (field.getAnnotation(Resource.class) == null)
return;
HttpSimpleClient httpClient = HttpSimpleClient.create(asyncGroup);
field.set(src, httpClient);
// 给其可能包含@Resource的字段赋值;
rf.inject(httpClient, null);
rf.register(resourceName, HttpSimpleClient.class, httpClient);
} catch (Exception e) {
logger.log(Level.SEVERE, "[" + Thread.currentThread().getName() + "] HttpClient inject error", e);
}
}, HttpSimpleClient.class);
// --------------------------------------------------------------------------
if (this.asyncGroup != null) {
((AsyncIOGroup) this.asyncGroup).start();
}
if (this.clusterAgent != null) {
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER, "ClusterAgent initing");
long s = System.currentTimeMillis();
if (this.clusterAgent instanceof CacheClusterAgent) {
// 必须在inject前调用,需要赋值Resourcable.name
String sourceName = ((CacheClusterAgent) clusterAgent).getSourceName();
loadCacheSource(sourceName);
}
clusterAgent.setTransportFactory(this.sncpTransportFactory);
this.resourceFactory.inject(clusterAgent);
clusterAgent.init(clusterAgent.getConfig());
this.resourceFactory.register(ClusterAgent.class, clusterAgent);
logger.info("ClusterAgent init in " + (System.currentTimeMillis() - s) + " ms");
}
if (this.messageAgents != null) {
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER, "MessageAgent initing");
long s = System.currentTimeMillis();
for (MessageAgent agent : this.messageAgents) {
this.resourceFactory.inject(agent);
agent.init(agent.getConfig());
this.resourceFactory.register(agent.getName(), MessageAgent.class, agent);
this.resourceFactory.register(agent.getName(), HttpMessageClient.class, agent.getHttpMessageClient());
// this.resourceFactory.register(agent.getName(), SncpMessageClient.class, agent.getSncpMessageClient()); //不需要给开发者使用
}
logger.info("MessageAgent init in " + (System.currentTimeMillis() - s) + " ms");
}
// ------------------------------------- 注册 HttpMessageClient --------------------------------------------------------
resourceFactory.register((ResourceFactory rf, final Object src, String resourceName, Field field, final Object attachment) -> {
try {
if (field.getAnnotation(Resource.class) == null)
return;
if (clusterAgent == null) {
HttpMessageClient messageClient = new HttpMessageLocalClient(application, resourceName);
field.set(src, messageClient);
// 给其可能包含@Resource的字段赋值;
rf.inject(messageClient, null);
rf.register(resourceName, HttpMessageClient.class, messageClient);
return;
}
HttpMessageClient messageClient = new HttpMessageClusterClient(application, resourceName, clusterAgent);
field.set(src, messageClient);
// 给其可能包含@Resource的字段赋值;
rf.inject(messageClient, null);
rf.register(resourceName, HttpMessageClient.class, messageClient);
} catch (Exception e) {
logger.log(Level.SEVERE, "[" + Thread.currentThread().getName() + "] HttpMessageClient inject error", e);
}
}, HttpMessageClient.class);
initResources();
}
Aggregations