下面列出了com.google.common.util.concurrent.Uninterruptibles#awaitUninterruptibly ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Nullable
public SourceChange setWidgetPropertyValue(int propertyId, FlutterWidgetPropertyValue value) {
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<SourceChange> result = new AtomicReference<>();
final String id = analysisService.generateUniqueId();
synchronized (responseConsumers) {
responseConsumers.put(id, (resultObject) -> {
try {
final JsonObject propertiesObject = resultObject.getAsJsonObject("change");
result.set(SourceChange.fromJson(propertiesObject));
}
catch (Throwable ignored) {
}
latch.countDown();
});
}
final JsonObject request = FlutterRequestUtilities.generateFlutterSetWidgetPropertyValue(id, propertyId, value);
analysisService.sendRequest(id, request);
Uninterruptibles.awaitUninterruptibly(latch, 100, TimeUnit.MILLISECONDS);
return result.get();
}
@Test
public void testFullRequest() throws Exception {
outputReceived = new CountDownLatch(1);
FullRequest requestIn = RequestBuilders.newGet("/").host("localhost").build();
channel.writeOutbound(requestIn);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
Http2Request requestOut = (Http2Request) requests.remove(0);
assertTrue(requestOut != null);
assertTrue(requestOut.payload instanceof Http2Headers);
assertEquals("GET", ((Http2Headers) requestOut.payload).method().toString());
assertEquals("/", ((Http2Headers) requestOut.payload).path());
assertTrue(requestOut.eos);
}
@Test
public void testFullRequest() throws Exception {
outputReceived = new CountDownLatch(1);
Http2Headers headers = new DefaultHttp2Headers().method("GET").path("/");
Http2Request requestIn = Http2Request.build(1, headers, true);
channel.writeInbound(requestIn);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
Request requestOut = requests.remove(0);
assertNotNull(requestOut);
assertTrue(requestOut instanceof FullRequest);
assertEquals("h2", requestOut.version());
assertEquals(HttpMethod.GET, requestOut.method());
assertEquals("/", requestOut.path());
assertFalse(requestOut.hasBody());
assertNotNull(requestOut.body());
assertEquals(0, requestOut.body().readableBytes());
assertEquals(1, requestOut.streamId());
}
@Test
public void testSendAsync() {
String subject = nextSubject();
CountDownLatch latch1 = new CountDownLatch(1);
CompletableFuture<Void> response = netty1.sendAsync(address2, subject, "hello world".getBytes());
response.whenComplete((r, e) -> {
assertNull(e);
latch1.countDown();
});
Uninterruptibles.awaitUninterruptibly(latch1);
CountDownLatch latch2 = new CountDownLatch(1);
response = netty1.sendAsync(invalidAddress, subject, "hello world".getBytes());
response.whenComplete((r, e) -> {
assertNotNull(e);
assertTrue(e instanceof ConnectException);
latch2.countDown();
});
Uninterruptibles.awaitUninterruptibly(latch2);
}
@Test
public void testFullRequest() throws Exception {
outputReceived = new CountDownLatch(1);
FullHttpRequest requestIn = new DefaultFullHttpRequest(HTTP_1_1, GET, "/");
channel.writeInbound(requestIn);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
Request requestOut = requests.remove(0);
assertTrue(requestOut != null);
assertTrue(requestOut instanceof FullRequest);
assertEquals("HTTP/1.1", requestOut.version());
assertEquals(HttpMethod.GET, requestOut.method());
assertEquals("/", requestOut.path());
assertFalse(requestOut.hasBody());
assertFalse(requestOut.body() == null);
assertEquals(0, requestOut.body().readableBytes());
}
@Test
public void testFullResponse() throws Exception {
outputReceived = new CountDownLatch(1);
Http2Headers headers = new DefaultHttp2Headers().status("200");
Http2Response responseIn = Http2Response.build(1, headers, true);
channel.writeInbound(responseIn);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
Response responseOut = responses.remove(0);
assertTrue(responseOut != null);
assertTrue(responseOut instanceof FullResponse);
assertEquals("h2", responseOut.version());
assertEquals(OK, responseOut.status());
assertFalse(responseOut.hasBody());
assertEquals(1, responseOut.streamId());
}
@Test
public void testFullRequestWithBody() throws Exception {
outputReceived = new CountDownLatch(1);
ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body");
FullRequest requestIn = RequestBuilders.newPost("/").body(body).build();
channel.writeOutbound(requestIn);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
FullHttpRequest requestOut = (FullHttpRequest) requests.remove(0);
assertTrue(requestOut != null);
assertEquals(HTTP_1_1, requestOut.protocolVersion());
assertEquals(HttpMethod.POST, requestOut.method());
assertEquals("/", requestOut.uri());
assertFalse(requestOut.content() == null);
assertEquals(body, requestOut.content());
}
void futureCallCallback() {
GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
ListenableFuture<HelloReply> response =
stub.sayHello(HelloRequest.newBuilder().setName("Maggie").build());
final CountDownLatch latch = new CountDownLatch(1);
Futures.addCallback(
response,
new FutureCallback<HelloReply>() {
@Override
public void onSuccess(@Nullable HelloReply result) {
// Won't be called, since the server in this example always fails.
}
@Override
public void onFailure(Throwable t) {
Status status = Status.fromThrowable(t);
Verify.verify(status.getCode() == Status.Code.INTERNAL);
Verify.verify(status.getDescription().contains("Crybaby"));
// Cause is not transmitted over the wire..
latch.countDown();
}
},
directExecutor());
if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
throw new RuntimeException("timeout!");
}
}
/**
* Executes a task, on N threads, all starting at the same time.
*
* @param nThreads the number of threads to execute
* @param task the task to execute in each thread
* @return the result of each task and the full execution time, in nanoseconds
*/
public static <T> TestResult<T> timeTasks(int nThreads, Callable<T> task) {
CountDownLatch startGate = new CountDownLatch(1);
CountDownLatch endGate = new CountDownLatch(nThreads);
AtomicReferenceArray<T> results = new AtomicReferenceArray<T>(nThreads);
for (int i = 0; i < nThreads; i++) {
final int index = i;
executor.execute(() -> {
try {
startGate.await();
try {
results.set(index, task.call());
} finally {
endGate.countDown();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
long start = System.nanoTime();
startGate.countDown();
Uninterruptibles.awaitUninterruptibly(endGate);
long end = System.nanoTime();
return new TestResult<T>(end - start, toList(results));
}
/**
* Put a dummy task into the queue and wait for it to be run. Because it's single threaded, this means all
* tasks submitted before this point are now completed. Usually you won't want to use this method - it's a
* convenience primarily used in unit testing. If you want to wait for an event to be called the right thing
* to do is usually to create a {@link com.google.common.util.concurrent.SettableFuture} and then call set
* on it. You can then either block on that future, compose it, add listeners to it and so on.
*/
public static void waitForUserCode() {
final CountDownLatch latch = new CountDownLatch(1);
USER_THREAD.execute(new Runnable() {
@Override
public void run() {
latch.countDown();
}
});
Uninterruptibles.awaitUninterruptibly(latch);
}
public int beginSheet() {
if(NSThread.isMainThread()) {
// No need to call invoke on main thread
if(controller != null) {
controller.loadBundle();
this.beginSheet(controller.window());
}
else {
this.beginSheet(window);
}
}
else {
final SheetInvoker invoker = this;
invoke(new DefaultMainAction() {
@Override
public void run() {
//Invoke again on main thread
if(controller != null) {
controller.loadBundle();
invoker.beginSheet(controller.window());
}
else {
invoker.beginSheet(window);
}
}
}, true);
if(log.isDebugEnabled()) {
log.debug("Await sheet dismiss");
}
// Synchronize on parent controller. Only display one sheet at once.
Uninterruptibles.awaitUninterruptibly(signal);
}
return returncode;
}
@Test
public void testAutomaticTaskProcessing() throws Throwable {
String queueName = UUID.randomUUID().toString();
WorkQueue<String> queue1 = atomix().<String>workQueueBuilder(queueName)
.withProtocol(protocol())
.build();
Executor executor = Executors.newSingleThreadExecutor();
CountDownLatch latch1 = new CountDownLatch(1);
queue1.registerTaskProcessor(s -> latch1.countDown(), 2, executor);
WorkQueue<String> queue2 = atomix().<String>workQueueBuilder(queueName)
.withProtocol(protocol())
.build();
String item1 = DEFAULT_PAYLOAD;
queue2.addOne(item1);
assertTrue(Uninterruptibles.awaitUninterruptibly(latch1, 5000, TimeUnit.MILLISECONDS));
queue1.stopProcessing();
String item2 = DEFAULT_PAYLOAD;
String item3 = DEFAULT_PAYLOAD;
Thread.sleep((int) DEFAULT_PROCESSING_TIME.toMillis());
queue2.addMultiple(Arrays.asList(item2, item3));
WorkQueueStats stats = queue1.stats();
assertEquals(2, stats.totalPending());
assertEquals(0, stats.totalInProgress());
assertEquals(1, stats.totalCompleted());
CountDownLatch latch2 = new CountDownLatch(2);
queue1.registerTaskProcessor(s -> latch2.countDown(), 2, executor);
Uninterruptibles.awaitUninterruptibly(latch2, 500, TimeUnit.MILLISECONDS);
}
@Test
public void testSslRequest() throws InterruptedException {
CountDownLatch receivedResponse = new CountDownLatch(2);
final ConcurrentLinkedQueue<HttpObject> responses = new ConcurrentLinkedQueue<>();
ChannelHandler responseHandler =
new SimpleChannelInboundHandler<HttpObject>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
responses.add(msg);
receivedResponse.countDown();
}
};
ClientConfig config = ClientConfig.fromConfig("xio.h1TestClient");
XioClientBootstrap bootstrap =
new XioClientBootstrap(config)
.channelConfig(ChannelConfiguration.clientConfig(1))
.handler(responseHandler);
HttpClientBuilder builder = new HttpClientBuilder(bootstrap);
URL url = server.url("/hello-world").url();
HttpClient client = builder.endpointForUrl(url).build();
client.write(Http.get("/hello-world"));
Uninterruptibles.awaitUninterruptibly(receivedResponse); // block
// check request
RecordedRequest request1 = server.takeRequest();
assertEquals("/hello-world", request1.getPath());
// check response
assertEquals(HttpResponseStatus.OK, ((HttpResponse) responses.poll()).status());
}
@Test
public void testFullRequestWithBody() throws Exception {
outputReceived = new CountDownLatch(1);
ByteBuf body = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body");
FullRequest requestIn = RequestBuilders.newPost("/").host("localhost").body(body).build();
channel.writeOutbound(requestIn);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
Http2Request requestOut = (Http2Request) requests.remove(0);
assertTrue(requestOut != null);
assertTrue(requestOut.payload instanceof Http2Headers);
assertEquals("POST", ((Http2Headers) requestOut.payload).method().toString());
assertEquals("/", ((Http2Headers) requestOut.payload).path());
assertFalse(requestOut.eos);
Http2Request contentOut = (Http2Request) requests.remove(0);
assertTrue(contentOut != null);
assertTrue(contentOut.payload instanceof Http2DataFrame);
assertEquals(body, ((Http2DataFrame) contentOut.payload).content());
assertTrue(contentOut.eos);
}
/**
* Put a dummy task into the queue and wait for it to be run. Because it's single threaded, this means all
* tasks submitted before this point are now completed. Usually you won't want to use this method - it's a
* convenience primarily used in unit testing. If you want to wait for an event to be called the right thing
* to do is usually to create a {@link com.google.common.util.concurrent.SettableFuture} and then call set
* on it. You can then either block on that future, compose it, add listeners to it and so on.
*/
public static void waitForUserCode() {
final CountDownLatch latch = new CountDownLatch(1);
USER_THREAD.execute(new Runnable() {
@Override public void run() {
latch.countDown();
}
});
Uninterruptibles.awaitUninterruptibly(latch);
}
@Test
public void testLargePayloadCanFailUpdateWithRetry() {
Task task = testTask();
Worker worker = mock(Worker.class);
when(worker.getPollingInterval()).thenReturn(3000);
when(worker.getTaskDefName()).thenReturn(TEST_TASK_DEF_NAME);
when(worker.execute(any())).thenReturn(new TaskResult(task));
TaskClient taskClient = Mockito.mock(TaskClient.class);
when(taskClient.pollTask(any(), any(), any())).thenReturn(task);
when(taskClient.ack(any(), any())).thenReturn(true);
doAnswer(invocation -> {
Object[] args = invocation.getArguments();
TaskResult result = (TaskResult) args[0];
assertNull(result.getReasonForIncompletion());
result.setReasonForIncompletion("some_reason");
throw new ConductorClientException();
}).when(taskClient).evaluateAndUploadLargePayload(any(TaskResult.class), any());
TaskPollExecutor taskPollExecutor = new TaskPollExecutor(null, taskClient, 1, 3, "test-worker-");
CountDownLatch latch = new CountDownLatch(1);
doAnswer(invocation -> {
latch.countDown();
return null;
}
).when(worker).onErrorUpdate(any());
Executors.newSingleThreadScheduledExecutor()
.scheduleAtFixedRate(() -> taskPollExecutor.pollAndExecute(worker), 0, 1, TimeUnit.SECONDS);
Uninterruptibles.awaitUninterruptibly(latch);
// When evaluateAndUploadLargePayload fails indefinitely, task update shouldn't be called.
verify(taskClient, times(0)).updateTask(any());
}
@Override
public void run() {
LOG.info(Compute.getMessage());
Uninterruptibles.awaitUninterruptibly(stopLatch);
}
@Test
public void testStreamingResponseWithTrailingHeaders() throws Exception {
outputReceived = new CountDownLatch(3);
Http2Headers headers = new DefaultHttp2Headers().status("200");
Http2Response responseIn = Http2Response.build(1, headers, false);
ByteBuf body1 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body1");
Http2Response content = Http2Response.build(1, new DefaultHttp2DataFrame(body1, false), false);
ByteBuf body2 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body2");
Http2Response lastContent =
Http2Response.build(1, new DefaultHttp2DataFrame(body2, false), false);
Http2Response trailers =
Http2Response.build(1, new DefaultHttp2Headers().set("foo", "bar"), true);
channel.writeInbound(responseIn);
channel.writeInbound(content);
channel.writeInbound(lastContent);
channel.writeInbound(trailers);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
SegmentedResponse responseOut = (SegmentedResponse) responses.remove(0);
assertTrue(responseOut != null);
assertEquals("h2", responseOut.version());
assertEquals(HttpResponseStatus.OK, responseOut.status());
assertFalse(responseOut.hasBody());
assertFalse(responseOut.body() == null);
assertEquals(0, responseOut.body().readableBytes());
SegmentedResponseData bodyOut1 = (SegmentedResponseData) responses.remove(0);
assertTrue(bodyOut1 != null);
assertEquals("h2", responseOut.version());
assertEquals(HttpResponseStatus.OK, responseOut.status());
assertFalse(bodyOut1.hasBody());
assertFalse(bodyOut1.body() == null);
assertFalse(bodyOut1.content() == null);
assertEquals(body1, bodyOut1.content());
assertFalse(bodyOut1.endOfMessage());
SegmentedResponseData bodyOut2 = (SegmentedResponseData) responses.remove(0);
assertTrue(bodyOut2 != null);
assertEquals("h2", responseOut.version());
assertEquals(HttpResponseStatus.OK, responseOut.status());
assertFalse(bodyOut2.hasBody());
assertFalse(bodyOut2.body() == null);
assertFalse(bodyOut2.content() == null);
assertEquals(body2, bodyOut2.content());
assertFalse(bodyOut2.endOfMessage());
SegmentedResponseData trailersOut = (SegmentedResponseData) responses.remove(0);
assertTrue(trailersOut != null);
assertEquals("h2", trailersOut.version());
assertEquals(HttpResponseStatus.OK, trailersOut.status());
assertFalse(trailersOut.hasBody());
assertFalse(trailersOut.body() == null);
assertEquals(0, trailersOut.body().readableBytes());
assertEquals(1, trailersOut.trailingHeaders().size());
assertEquals("bar", trailersOut.trailingHeaders().get("foo"));
assertTrue(trailersOut.endOfMessage());
}
@Test
public void testStreamingRequest() throws Exception {
outputReceived = new CountDownLatch(3);
HttpRequest requestIn = new DefaultHttpRequest(HTTP_1_1, GET, "/");
ByteBuf body1 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body1");
HttpContent content = new DefaultHttpContent(body1);
ByteBuf body2 = ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "body2");
LastHttpContent lastContent = new DefaultLastHttpContent(body2);
channel.writeInbound(requestIn);
channel.writeInbound(content);
channel.writeInbound(lastContent);
channel.runPendingTasks(); // blocks
Uninterruptibles.awaitUninterruptibly(outputReceived);
Request requestOut = requests.remove(0);
assertTrue(requestOut != null);
assertTrue(requestOut instanceof SegmentedRequest);
assertEquals("HTTP/1.1", requestOut.version());
assertEquals(HttpMethod.GET, requestOut.method());
assertEquals("/", requestOut.path());
assertFalse(requestOut.hasBody());
assertFalse(requestOut.body() == null);
assertEquals(0, requestOut.body().readableBytes());
Request bodyOut1 = requests.remove(0);
assertTrue(bodyOut1 != null);
assertTrue(bodyOut1 instanceof SegmentedRequestData);
assertEquals("HTTP/1.1", bodyOut1.version());
assertEquals(HttpMethod.GET, bodyOut1.method());
assertEquals("/", bodyOut1.path());
assertFalse(bodyOut1.hasBody());
assertFalse(bodyOut1.body() == null);
assertFalse(((SegmentedRequestData) bodyOut1).content() == null);
assertEquals(body1, ((SegmentedRequestData) bodyOut1).content());
assertFalse(((SegmentedRequestData) bodyOut1).endOfMessage());
Request bodyOut2 = requests.remove(0);
assertTrue(bodyOut2 != null);
assertTrue(bodyOut2 instanceof SegmentedRequestData);
assertEquals("HTTP/1.1", bodyOut2.version());
assertEquals(HttpMethod.GET, bodyOut2.method());
assertEquals("/", bodyOut2.path());
assertFalse(bodyOut2.hasBody());
assertFalse(bodyOut2.body() == null);
assertFalse(((SegmentedRequestData) bodyOut2).content() == null);
assertEquals(body2, ((SegmentedRequestData) bodyOut2).content());
assertTrue(((SegmentedRequestData) bodyOut2).endOfMessage());
}
protected Exit edit(final SessionPool session, final Path remote) throws BackgroundException {
final EditorFactory factory = EditorFactory.instance();
final Application application;
final ApplicationFinder finder = ApplicationFinderFactory.get();
if(StringUtils.isNotBlank(input.getOptionValue(TerminalOptionsBuilder.Params.application.name()))) {
application = finder.getDescription(input.getOptionValue(TerminalOptionsBuilder.Params.application.name()));
if(!finder.isInstalled(application)) {
throw new BackgroundException(LocaleFactory.localizedString("Unknown"),
String.format("Application %s not found", input.getOptionValue(TerminalOptionsBuilder.Params.application.name())));
}
}
else {
application = factory.getEditor(remote.getName());
}
if(!finder.isInstalled(application)) {
throw new BackgroundException(LocaleFactory.localizedString("Unknown"),
String.format("No application found to edit %s", remote.getName()));
}
final Editor editor = factory.create(controller, session, application, remote);
final CountDownLatch lock = new CountDownLatch(1);
final Worker<Transfer> worker = editor.open(new ApplicationQuitCallback() {
@Override
public void callback() {
lock.countDown();
}
}, new DisabledTransferErrorCallback(), new DefaultEditorListener(controller, session, editor, new DefaultEditorListener.Listener() {
@Override
public void saved() {
//
}
}));
final SessionBackgroundAction<Transfer> action = new TerminalBackgroundAction<Transfer>(controller, session, worker);
try {
this.execute(action);
}
catch(TerminalBackgroundException e) {
return Exit.failure;
}
Uninterruptibles.awaitUninterruptibly(lock);
return Exit.success;
}