use of java.util.function.Function in project vert.x by eclipse.
the class MetricsContextTest method testHttpServerRequest.
private void testHttpServerRequest(Function<Vertx, Context> contextFactory, BiConsumer<Thread, Context> checker) throws Exception {
AtomicReference<Thread> expectedThread = new AtomicReference<>();
AtomicReference<Context> expectedContext = new AtomicReference<>();
AtomicBoolean requestBeginCalled = new AtomicBoolean();
AtomicBoolean responseEndCalled = new AtomicBoolean();
AtomicBoolean socketConnectedCalled = new AtomicBoolean();
AtomicBoolean socketDisconnectedCalled = new AtomicBoolean();
AtomicBoolean bytesReadCalled = new AtomicBoolean();
AtomicBoolean bytesWrittenCalled = new AtomicBoolean();
AtomicBoolean closeCalled = new AtomicBoolean();
VertxMetricsFactory factory = (vertx, options) -> new DummyVertxMetrics() {
@Override
public HttpServerMetrics createMetrics(HttpServer server, SocketAddress localAddress, HttpServerOptions options) {
return new DummyHttpServerMetrics() {
@Override
public Void requestBegin(Void socketMetric, HttpServerRequest request) {
requestBeginCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
return null;
}
@Override
public void responseEnd(Void requestMetric, HttpServerResponse response) {
responseEndCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
}
@Override
public Void connected(SocketAddress remoteAddress, String remoteName) {
socketConnectedCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
return null;
}
@Override
public void disconnected(Void socketMetric, SocketAddress remoteAddress) {
socketDisconnectedCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
}
@Override
public void bytesRead(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
bytesReadCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
}
@Override
public void bytesWritten(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
bytesWrittenCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public void close() {
closeCalled.set(true);
}
};
}
};
CountDownLatch latch = new CountDownLatch(1);
Vertx vertx = vertx(new VertxOptions().setMetricsOptions(new MetricsOptions().setEnabled(true).setFactory(factory)));
Context ctx = contextFactory.apply(vertx);
ctx.runOnContext(v1 -> {
HttpServer server = vertx.createHttpServer().requestHandler(req -> {
HttpServerResponse response = req.response();
response.setStatusCode(200).setChunked(true).write("bye").end();
response.close();
});
server.listen(8080, "localhost", onSuccess(s -> {
expectedThread.set(Thread.currentThread());
expectedContext.set(Vertx.currentContext());
latch.countDown();
}));
});
awaitLatch(latch);
HttpClient client = vertx.createHttpClient();
client.put(8080, "localhost", "/", resp -> {
resp.netSocket().closeHandler(v -> {
vertx.close(v4 -> {
assertTrue(requestBeginCalled.get());
assertTrue(responseEndCalled.get());
assertTrue(bytesReadCalled.get());
assertTrue(bytesWrittenCalled.get());
assertTrue(socketConnectedCalled.get());
assertTrue(socketDisconnectedCalled.get());
assertTrue(closeCalled.get());
testComplete();
});
});
}).exceptionHandler(err -> {
fail(err.getMessage());
}).setChunked(true).write(Buffer.buffer("hello")).end();
await();
}
use of java.util.function.Function in project vert.x by eclipse.
the class MetricsContextTest method testHttpClientRequest.
private void testHttpClientRequest(Function<Vertx, Context> contextFactory, BiConsumer<Thread, Context> checker) throws Exception {
AtomicReference<Thread> expectedThread = new AtomicReference<>();
AtomicReference<Context> expectedContext = new AtomicReference<>();
AtomicBoolean requestBeginCalled = new AtomicBoolean();
AtomicBoolean responseEndCalled = new AtomicBoolean();
AtomicBoolean socketConnectedCalled = new AtomicBoolean();
AtomicBoolean socketDisconnectedCalled = new AtomicBoolean();
AtomicBoolean bytesReadCalled = new AtomicBoolean();
AtomicBoolean bytesWrittenCalled = new AtomicBoolean();
AtomicBoolean closeCalled = new AtomicBoolean();
VertxMetricsFactory factory = (vertx, options) -> new DummyVertxMetrics() {
@Override
public HttpClientMetrics createMetrics(HttpClient client, HttpClientOptions options) {
return new DummyHttpClientMetrics() {
@Override
public Void requestBegin(Void endpointMetric, Void socketMetric, SocketAddress localAddress, SocketAddress remoteAddress, HttpClientRequest request) {
requestBeginCalled.set(true);
return null;
}
@Override
public void responseEnd(Void requestMetric, HttpClientResponse response) {
responseEndCalled.set(true);
}
@Override
public Void connected(SocketAddress remoteAddress, String remoteName) {
socketConnectedCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
return null;
}
@Override
public void disconnected(Void socketMetric, SocketAddress remoteAddress) {
socketDisconnectedCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
}
@Override
public void bytesRead(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
bytesReadCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
}
@Override
public void bytesWritten(Void socketMetric, SocketAddress remoteAddress, long numberOfBytes) {
bytesWrittenCalled.set(true);
checker.accept(expectedThread.get(), expectedContext.get());
}
@Override
public void close() {
closeCalled.set(true);
}
@Override
public boolean isEnabled() {
return true;
}
};
}
};
Vertx vertx = vertx(new VertxOptions().setMetricsOptions(new MetricsOptions().setEnabled(true).setFactory(factory)));
HttpServer server = vertx.createHttpServer();
server.requestHandler(req -> {
req.endHandler(buf -> {
HttpServerResponse resp = req.response();
resp.setChunked(true).write(Buffer.buffer("bye")).end();
resp.close();
});
});
CountDownLatch latch = new CountDownLatch(1);
server.listen(8080, "localhost", onSuccess(s -> {
latch.countDown();
}));
awaitLatch(latch);
Context ctx = contextFactory.apply(vertx);
ctx.runOnContext(v1 -> {
expectedThread.set(Thread.currentThread());
expectedContext.set(Vertx.currentContext());
HttpClient client = vertx.createHttpClient();
checker.accept(expectedThread.get(), expectedContext.get());
HttpClientRequest req = client.put(8080, "localhost", "/");
req.handler(resp -> {
executeInVanillaThread(() -> {
client.close();
vertx.close(v2 -> {
assertTrue(requestBeginCalled.get());
assertTrue(responseEndCalled.get());
assertTrue(socketConnectedCalled.get());
assertTrue(socketDisconnectedCalled.get());
assertTrue(bytesReadCalled.get());
assertTrue(bytesWrittenCalled.get());
assertTrue(closeCalled.get());
testComplete();
});
});
});
req.setChunked(true).write("hello");
req.end();
});
await();
}
use of java.util.function.Function in project elasticsearch by elastic.
the class CandidateQueryTests method testDuel.
public void testDuel() throws Exception {
List<Function<String, Query>> queryFunctions = new ArrayList<>();
queryFunctions.add((id) -> new PrefixQuery(new Term("field", id)));
queryFunctions.add((id) -> new WildcardQuery(new Term("field", id + "*")));
queryFunctions.add((id) -> new CustomQuery(new Term("field", id)));
queryFunctions.add((id) -> new SpanTermQuery(new Term("field", id)));
queryFunctions.add((id) -> new TermQuery(new Term("field", id)));
queryFunctions.add((id) -> {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
return builder.build();
});
queryFunctions.add((id) -> {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(new TermQuery(new Term("field", id)), BooleanClause.Occur.MUST);
if (randomBoolean()) {
builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
}
if (randomBoolean()) {
builder.add(new CustomQuery(new Term("field", id)), BooleanClause.Occur.MUST);
}
return builder.build();
});
queryFunctions.add((id) -> {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(new TermQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
if (randomBoolean()) {
builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
}
if (randomBoolean()) {
builder.add(new CustomQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
}
return builder.build();
});
queryFunctions.add((id) -> {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
if (randomBoolean()) {
builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
}
return builder.build();
});
queryFunctions.add((id) -> {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.SHOULD);
builder.add(new MatchAllDocsQuery(), BooleanClause.Occur.SHOULD);
if (randomBoolean()) {
builder.add(new MatchNoDocsQuery("no reason"), BooleanClause.Occur.MUST_NOT);
}
return builder.build();
});
queryFunctions.add((id) -> {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.setMinimumNumberShouldMatch(randomIntBetween(0, 4));
builder.add(new TermQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
builder.add(new CustomQuery(new Term("field", id)), BooleanClause.Occur.SHOULD);
return builder.build();
});
queryFunctions.add((id) -> new MatchAllDocsQuery());
queryFunctions.add((id) -> new MatchNoDocsQuery("no reason at all"));
int numDocs = randomIntBetween(queryFunctions.size(), queryFunctions.size() * 3);
List<ParseContext.Document> documents = new ArrayList<>();
for (int i = 0; i < numDocs; i++) {
String id = Integer.toString(i);
Query query = queryFunctions.get(i % queryFunctions.size()).apply(id);
addQuery(query, documents);
}
indexWriter.addDocuments(documents);
indexWriter.close();
directoryReader = DirectoryReader.open(directory);
IndexSearcher shardSearcher = newSearcher(directoryReader);
// Disable query cache, because ControlQuery cannot be cached...
shardSearcher.setQueryCache(null);
for (int i = 0; i < numDocs; i++) {
String id = Integer.toString(i);
Iterable<? extends IndexableField> doc = Collections.singleton(new StringField("field", id, Field.Store.NO));
MemoryIndex memoryIndex = MemoryIndex.fromDocument(doc, new WhitespaceAnalyzer());
duelRun(queryStore, memoryIndex, shardSearcher);
}
Iterable<? extends IndexableField> doc = Collections.singleton(new StringField("field", "value", Field.Store.NO));
MemoryIndex memoryIndex = MemoryIndex.fromDocument(doc, new WhitespaceAnalyzer());
duelRun(queryStore, memoryIndex, shardSearcher);
// Empty percolator doc:
memoryIndex = new MemoryIndex();
duelRun(queryStore, memoryIndex, shardSearcher);
}
use of java.util.function.Function in project elasticsearch by elastic.
the class MapperServiceTests method testTotalFieldsExceedsLimit.
public void testTotalFieldsExceedsLimit() throws Throwable {
Function<String, String> mapping = type -> {
try {
return XContentFactory.jsonBuilder().startObject().startObject(type).startObject("properties").startObject("field1").field("type", "keyword").endObject().endObject().endObject().endObject().string();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
};
createIndex("test1").mapperService().merge("type", new CompressedXContent(mapping.apply("type")), MergeReason.MAPPING_UPDATE, false);
//set total number of fields to 1 to trigger an exception
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> {
createIndex("test2", Settings.builder().put(MapperService.INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING.getKey(), 1).build()).mapperService().merge("type", new CompressedXContent(mapping.apply("type")), MergeReason.MAPPING_UPDATE, false);
});
assertTrue(e.getMessage(), e.getMessage().contains("Limit of total fields [1] in index [test2] has been exceeded"));
}
use of java.util.function.Function in project elasticsearch by elastic.
the class IndexShardOperationsLockTests method testThreadContextPreservedIfBlock.
/**
* Tests that the ThreadContext is restored when a operation is executed after it has been delayed due to a block
*/
public void testThreadContextPreservedIfBlock() throws ExecutionException, InterruptedException, TimeoutException {
final ThreadContext context = threadPool.getThreadContext();
final Function<ActionListener<Releasable>, Boolean> contextChecker = (listener) -> {
if ("bar".equals(context.getHeader("foo")) == false) {
listener.onFailure(new IllegalStateException("context did not have value [bar] for header [foo]. Actual value [" + context.getHeader("foo") + "]"));
} else if ("baz".equals(context.getTransient("bar")) == false) {
listener.onFailure(new IllegalStateException("context did not have value [baz] for transient [bar]. Actual value [" + context.getTransient("bar") + "]"));
} else {
return true;
}
return false;
};
PlainActionFuture<Releasable> future = new PlainActionFuture<Releasable>() {
@Override
public void onResponse(Releasable releasable) {
if (contextChecker.apply(this)) {
super.onResponse(releasable);
}
}
};
PlainActionFuture<Releasable> future2 = new PlainActionFuture<Releasable>() {
@Override
public void onResponse(Releasable releasable) {
if (contextChecker.apply(this)) {
super.onResponse(releasable);
}
}
};
try (Releasable releasable = blockAndWait()) {
// when the releasable is closed
try (ThreadContext.StoredContext ignore = context.newStoredContext(false)) {
context.putHeader("foo", "bar");
context.putTransient("bar", "baz");
// test both with and without a executor name
block.acquire(future, ThreadPool.Names.GENERIC, true);
block.acquire(future2, null, true);
}
assertFalse(future.isDone());
}
future.get(1, TimeUnit.HOURS).close();
future2.get(1, TimeUnit.HOURS).close();
}
Aggregations