io.vertx.reactivex.core.buffer.Buffer Java Examples
The following examples show how to use
io.vertx.reactivex.core.buffer.Buffer.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RxifiedExamples.java From vertx-rx with Apache License 2.0 | 6 votes |
public void writeStreamSubscriberAdapterCallbacks(Flowable<Buffer> flowable, HttpServerResponse response) { response.setChunked(true); WriteStreamSubscriber<Buffer> subscriber = response.toSubscriber(); subscriber.onError(throwable -> { if (!response.headWritten() && response.closed()) { response.setStatusCode(500).end("oops"); } else { // log error } }); subscriber.onWriteStreamError(throwable -> { // log error }); subscriber.onWriteStreamEnd(() -> { // log end of transaction to audit system... }); flowable.subscribe(subscriber); }
Example #2
Source File: RxifiedExamples.java From vertx-rx with Apache License 2.0 | 6 votes |
public void delayFlowable(HttpServer server) { server.requestHandler(request -> { if (request.method() == HttpMethod.POST) { // Stop receiving buffers request.pause(); checkAuth(res -> { // Now we can receive buffers again request.resume(); if (res.succeeded()) { Flowable<Buffer> flowable = request.toFlowable(); flowable.subscribe(buff -> { // Get buffers }); } }); } }); }
Example #3
Source File: ProdMailer.java From redpipe with Apache License 2.0 | 6 votes |
@Override public Completable send(Mail email) { Single<Optional<Buffer>> htmlRender = email.renderHtml().map(buffer -> Optional.of(buffer)).toSingle(Optional.empty()); Single<Buffer> textRender = email.renderText(); return Single.zip(textRender, htmlRender, (text, html) -> { MailMessage message = new MailMessage(); message.setFrom(email.from); if(email.to != null) message.setTo(Arrays.asList(email.to)); if(email.cc != null) message.setCc(Arrays.asList(email.cc)); if(email.bcc != null) message.setBcc(Arrays.asList(email.bcc)); message.setSubject(email.subject); message.setText(text.toString()); if(html.isPresent()) message.setHtml(html.get().toString()); return mailClient.rxSendMail(message).ignoreElement(); }).flatMapCompletable(c -> c); }
Example #4
Source File: PermissionEndpointTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void success_extendedRequest() { PermissionTicket success = new PermissionTicket().setId("success"); final String extendedRequest = "[{\"resource_id\":\"{{set_one}}\", \"resource_scopes\":[\"profile:read\"]}, {\"resource_id\":\"{{set_two}}\",\"resource_scopes\":[\"avatar:write\"]}]"; when(context.getBody()).thenReturn(Buffer.buffer(extendedRequest)); when(context.response()).thenReturn(response); when(response.putHeader(anyString(),anyString())).thenReturn(response); when(response.setStatusCode(anyInt())).thenReturn(response); when(permissionTicketService.create(anyList(), eq(DOMAIN_ID), eq(CLIENT_ID))).thenReturn(Single.just(success)); endpoint.handle(context); verify(response, times(1)).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); verify(context.response(), times(1)).setStatusCode(intCaptor.capture()); verify(context.response(), times(1)).end(strCaptor.capture()); Assert.assertEquals("Expecting 201 creation status",intCaptor.getValue().intValue(),201); Assert.assertTrue("Expect success id", strCaptor.getValue().contains("success")); }
Example #5
Source File: ApiTest.java From redpipe with Apache License 2.0 | 6 votes |
private void checkRequest(int expectedStatus, String expectedBody, String url, TestContext context, String authHeader) { Async async = context.async(); HttpRequest<Buffer> request = webClient .get(url); if(authHeader != null) request.putHeader(HttpHeaders.AUTHORIZATION, authHeader); request.as(BodyCodec.string()) .rxSend() .map(r -> { context.assertEquals(expectedStatus, r.statusCode()); if(expectedBody != IGNORE) context.assertEquals(expectedBody, r.body()); return r; }) .doOnError(context::fail) .subscribe(response -> async.complete()); }
Example #6
Source File: PermissionEndpointTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void success_simpleRequest() { PermissionTicket success = new PermissionTicket().setId("success"); final String simpleRequest = "{\"resource_id\":\"{{set_one}}\", \"resource_scopes\":[\"profile:read\"]}"; when(context.getBody()).thenReturn(Buffer.buffer(simpleRequest)); when(context.response()).thenReturn(response); when(response.putHeader(anyString(),anyString())).thenReturn(response); when(response.setStatusCode(anyInt())).thenReturn(response); when(permissionTicketService.create(anyList(), eq(DOMAIN_ID), eq(CLIENT_ID))).thenReturn(Single.just(success)); endpoint.handle(context); verify(response, times(1)).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); verify(context.response(), times(1)).setStatusCode(intCaptor.capture()); verify(context.response(), times(1)).end(strCaptor.capture()); Assert.assertEquals("Expecting 201 creation status",intCaptor.getValue().intValue(),201); Assert.assertTrue("Expect success id", strCaptor.getValue().contains("success")); }
Example #7
Source File: WebClientTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@Test public void testPost() { int times = 5; waitFor(times); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> req.bodyHandler(buff -> { assertEquals("onetwothree", buff.toString()); req.response().end(); })); try { server.listen(ar -> { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Observable<Buffer> stream = Observable.just(Buffer.buffer("one"), Buffer.buffer("two"), Buffer.buffer("three")); Single<HttpResponse<Buffer>> single = client .post(8080, "localhost", "/the_uri") .rxSendStream(stream); for (int i = 0; i < times; i++) { single.subscribe(resp -> complete(), this::fail); } }); await(); } finally { server.close(); } }
Example #8
Source File: DynamicClientRegistrationServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_sectorIdentifierUri_validRedirectUri() { final String redirectUri = "https://graviee.io/callback"; final String sectorUri = "https://sector/uri"; DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest(); request.setRedirectUris(Optional.of(Arrays.asList(redirectUri))); request.setSectorIdentifierUri(Optional.of(sectorUri)); HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); when(webClient.getAbs(sectorUri)).thenReturn(httpRequest); when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); when(httpResponse.bodyAsString()).thenReturn("[\""+redirectUri+"\"]"); TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test(); testObserver.assertNoErrors(); testObserver.assertComplete(); }
Example #9
Source File: DynamicClientRegistrationServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_sectorIdentifierUri_invalidRedirectUri() { final String sectorUri = "https://sector/uri"; DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest(); request.setRedirectUris(Optional.of(Arrays.asList("https://graviee.io/callback"))); request.setSectorIdentifierUri(Optional.of(sectorUri));//fail due to invalid url HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); when(webClient.getAbs(sectorUri)).thenReturn(httpRequest); when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); when(httpResponse.bodyAsString()).thenReturn("[\"https://not/same/redirect/uri\"]"); TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test(); testObserver.assertError(InvalidRedirectUriException.class); testObserver.assertNotComplete(); }
Example #10
Source File: CurrencyServiceProxy.java From vertx-kubernetes-workshop with Apache License 2.0 | 6 votes |
/** * Method to check the proxy requesting to convert the current portfolio to EUR. * * @param rc the routing context */ private void convertPortfolioToEuro(RoutingContext rc) { EventBusService.getServiceProxy(discovery, svc -> svc.getName().equals("portfolio"), PortfolioService.class, ar -> { if (ar.failed()) { rc.fail(ar.cause()); } else { ar.result().evaluate(res -> { if (res.failed()) { rc.fail(res.cause()); } else { JsonObject payload = new JsonObject().put("amount", res.result()).put("currency", "EUR"); rc.setBody(new Buffer(payload.toBuffer())); delegateWithCircuitBreaker(rc); } }); } }); }
Example #11
Source File: DynamicClientRegistrationServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void create_sectorIdentifierUriBadRequest() { final String sectorUri = "https://sector/uri"; DynamicClientRegistrationRequest request = new DynamicClientRegistrationRequest(); request.setRedirectUris(Optional.empty()); request.setSectorIdentifierUri(Optional.of(sectorUri));//fail due to invalid url HttpRequest<Buffer> httpRequest = Mockito.mock(HttpRequest.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); when(webClient.getAbs(sectorUri)).thenReturn(httpRequest); when(httpRequest.rxSend()).thenReturn(Single.just(httpResponse)); TestObserver<Client> testObserver = dcrService.create(request, BASE_PATH).test(); testObserver.assertError(InvalidClientMetadataException.class); testObserver.assertNotComplete(); assertTrue("Should have only one exception", testObserver.errorCount()==1); assertTrue("Unexpected start of error message", testObserver.errors().get(0).getMessage().startsWith("Unable to parse sector_identifier_uri")); }
Example #12
Source File: JWKServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void testGetClientKeys_fromJksUriProperty() { Client client = new Client(); client.setJwksUri(JWKS_URI); HttpRequest<Buffer> request = Mockito.mock(HttpRequest.class); HttpResponse<Buffer> response = Mockito.mock(HttpResponse.class); String bodyAsString = "{\"keys\":[{\"kty\": \"RSA\",\"use\": \"enc\",\"kid\": \"KID\",\"n\": \"modulus\",\"e\": \"exponent\"}]}"; when(webClient.getAbs(any())).thenReturn(request); when(request.rxSend()).thenReturn(Single.just(response)); when(response.bodyAsString()).thenReturn(bodyAsString); TestObserver testObserver = jwkService.getKeys(client).test(); testObserver.assertNoErrors(); testObserver.assertComplete(); testObserver.assertValue(jwkSet -> ((JWKSet)jwkSet).getKeys().get(0).getKid().equals("KID")); }
Example #13
Source File: JWKServiceTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void testGetKeys() { HttpRequest<Buffer> request = Mockito.mock(HttpRequest.class); HttpResponse<Buffer> response = Mockito.mock(HttpResponse.class); String bodyAsString = "{\"keys\":[{\"kty\": \"RSA\",\"use\": \"enc\",\"kid\": \"KID\",\"n\": \"modulus\",\"e\": \"exponent\"}]}"; when(webClient.getAbs(any())).thenReturn(request); when(request.rxSend()).thenReturn(Single.just(response)); when(response.bodyAsString()).thenReturn(bodyAsString); TestObserver testObserver = jwkService.getKeys(JWKS_URI).test(); testObserver.assertNoErrors(); testObserver.assertComplete(); testObserver.assertValue(jwkSet -> ((JWKSet)jwkSet).getKeys().get(0).getKid().equals("KID")); }
Example #14
Source File: CurrencyServiceProxy.java From vertx-kubernetes-workshop with Apache License 2.0 | 6 votes |
private void delegateWithCircuitBreaker(RoutingContext rc) { HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service")) .flatMap(client -> { // TODO // Use the circuit breaker (circuit) to call the service. Use the rxExecuteCommandWithFallback` method. // This methods takes 2 parameters: the first one if a function taking a `Future` as parameter and // needs to report the success or failure on this future. The second method is a function providing // the fallback result. You must provide a JSON object as response. For the fallback use: // new JsonObject() // .put("amount", rc.getBodyAsJson().getDouble("amount")) // .put("currency", "USD")) // In the first function, use the given client, emit a POST request on / containing the incoming // payload (rc.getBodyAsJson()). Extract the response payload as JSON (bodyAsJsonObject). Don't // forget to subscribe (you can use subscribe(toObserver(fut)). You can have a look to the `delegate` // method as example. // ----- return Single.just(new JsonObject().put("amount", 0.0).put("currency", "N/A")); }) // ---- .map(JsonObject::toBuffer) .map(Buffer::new) .subscribe(toObserver(rc)); }
Example #15
Source File: WebClientTest.java From vertx-rx with Apache License 2.0 | 6 votes |
@Test public void testResponseMissingBody() throws Exception { int times = 5; waitFor(times); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080)); server.requestStream().handler(req -> req.response().setStatusCode(403).end()); try { server.listen(ar -> { client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions())); Single<HttpResponse<Buffer>> single = client .get(8080, "localhost", "/the_uri") .rxSend(); for (int i = 0; i < times; i++) { single.subscribe(resp -> { assertEquals(403, resp.statusCode()); assertNull(resp.body()); complete(); }, this::fail); } }); await(); } finally { server.close(); } }
Example #16
Source File: PasswordPolicyRequestParseHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void shouldNotHandle_invalid_password() throws Exception { router.route("/") .handler(passwordPolicyRequestParseHandler) .handler(rc -> rc.response().end()); when(passwordValidator.validate(anyString())).thenReturn(false); testRequest(HttpMethod.POST, "/", req -> { Buffer buffer = Buffer.buffer(); buffer.appendString("password=password"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "application/x-www-form-urlencoded"); req.write(buffer); }, resp -> { String location = resp.headers().get("location"); assertNotNull(location); assertTrue(location.contains("warning=invalid_password_value")); },302, "Found", null); }
Example #17
Source File: PasswordPolicyRequestParseHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 6 votes |
@Test public void shouldHandle() throws Exception { router.route("/") .handler(passwordPolicyRequestParseHandler) .handler(rc -> rc.response().end()); when(passwordValidator.validate(anyString())).thenReturn(true); testRequest(HttpMethod.POST, "/", req -> { Buffer buffer = Buffer.buffer(); buffer.appendString("password=password"); req.headers().set("content-length", String.valueOf(buffer.length())); req.headers().set("content-type", "application/x-www-form-urlencoded"); req.write(buffer); },200, "OK", null); }
Example #18
Source File: CustomerRepository.java From Hands-On-Cloud-Native-Applications-with-Java-and-Quarkus with MIT License | 6 votes |
public CompletionStage<String> writeFile() { CompletableFuture<String> future = new CompletableFuture<>(); StringBuffer sb = new StringBuffer("id,name,surname"); sb.append("\n"); Observable.fromIterable(customerList) .map(c -> c.getId() + "," + c.getName() + "," + c.getSurname() + "\n") .subscribe( data -> sb.append(data), error -> System.err.println(error), () -> vertx.fileSystem().writeFile(path, Buffer.buffer(sb.toString()), handler -> { if (handler.succeeded()) { future.complete("File written in "+path); } else { System.err.println("Error while writing in file: " + handler.cause().getMessage()); } })); return future; }
Example #19
Source File: PermissionEndpointTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void handle_scopeIsEmpty() { when(context.getBody()).thenReturn(Buffer.buffer("{\"resource_id\":\"id\", \"resource_scopes\":[\"\"]}")); endpoint.handle(context); verify(context,times(1)).fail(errCaptor.capture()); Assert.assertTrue(errCaptor.getValue() instanceof InvalidRequestException); }
Example #20
Source File: GithubAuthenticationProvider.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private Maybe<String> authenticate(Authentication authentication) { // prepare body request parameters final String authorizationCode = authentication.getContext().request().parameters().getFirst(configuration.getCodeParameter()); if (authorizationCode == null || authorizationCode.isEmpty()) { LOGGER.debug("Authorization code is missing, skip authentication"); return Maybe.error(new BadCredentialsException("Missing authorization code")); } List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair(CLIENT_ID, configuration.getClientId())); urlParameters.add(new BasicNameValuePair(CLIENT_SECRET, configuration.getClientSecret())); urlParameters.add(new BasicNameValuePair(REDIRECT_URI, (String) authentication.getContext().get(REDIRECT_URI))); urlParameters.add(new BasicNameValuePair(CODE, authorizationCode)); String bodyRequest = URLEncodedUtils.format(urlParameters); return client.postAbs(configuration.getAccessTokenUri()) .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(bodyRequest.length())) .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED) .rxSendBuffer(Buffer.buffer(bodyRequest)) .toMaybe() .map(httpResponse -> { if (httpResponse.statusCode() != 200) { throw new BadCredentialsException(httpResponse.statusMessage()); } Map<String, String> bodyResponse = URLEncodedUtils.format(httpResponse.bodyAsString()); return bodyResponse.get("access_token"); }); }
Example #21
Source File: DefaultReactor.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private void sendNotFound(HttpServerResponse serverResponse) { // Send a NOT_FOUND HTTP status code (404) serverResponse.setStatusCode(HttpStatusCode.NOT_FOUND_404); String message = environment.getProperty("http.errors[404].message", "No security domain matches the request URI."); serverResponse.headers().set(HttpHeaders.CONTENT_LENGTH, Integer.toString(message.length())); serverResponse.headers().set(HttpHeaders.CONTENT_TYPE, "text/plain"); serverResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE); serverResponse.write(Buffer.buffer(message)); serverResponse.end(); }
Example #22
Source File: PermissionEndpointTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void handle_missingResourceId() { when(context.getBody()).thenReturn(Buffer.buffer("{\"unknown\":\"object\"}")); endpoint.handle(context); verify(context,times(1)).fail(errCaptor.capture()); Assert.assertTrue(errCaptor.getValue() instanceof InvalidRequestException); }
Example #23
Source File: RxifiedExamples.java From vertx-rx with Apache License 2.0 | 5 votes |
public void unmarshaller(FileSystem fileSystem) { fileSystem.open("/data.txt", new OpenOptions(), result -> { AsyncFile file = result.result(); Observable<Buffer> observable = file.toObservable(); observable.compose(ObservableHelper.unmarshaller((MyPojo.class))).subscribe( mypojo -> { // Process the object } ); }); }
Example #24
Source File: RxifiedExamples.java From vertx-rx with Apache License 2.0 | 5 votes |
public void websocketServerBuffer(Flowable<ServerWebSocket> socketObservable) { socketObservable.subscribe( socket -> { Observable<Buffer> dataObs = socket.toObservable(); dataObs.subscribe(buffer -> { System.out.println("Got message " + buffer.toString("UTF-8")); }); } ); }
Example #25
Source File: RxifiedExamples.java From vertx-rx with Apache License 2.0 | 5 votes |
public void websocketClientBuffer(Flowable<WebSocket> socketObservable) { socketObservable.subscribe( socket -> { Flowable<Buffer> dataObs = socket.toFlowable(); dataObs.subscribe(buffer -> { System.out.println("Got message " + buffer.toString("UTF-8")); }); } ); }
Example #26
Source File: RxifiedExamples.java From vertx-rx with Apache License 2.0 | 5 votes |
public void httpClientResponse(HttpClient client) { Single<HttpClientResponse> request = client.rxGet( 8080, "localhost", "/the_uri"); request.subscribe( response -> { Observable<Buffer> observable = response.toObservable(); observable.forEach( buffer -> { // Process buffer } ); } ); }
Example #27
Source File: UserInfoEndpointHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void shouldInvokeUserEndpoint_post() throws Exception { User user = new User(); user.setAdditionalInformation(Collections.singletonMap("sub", "user")); JWT jwt = new JWT(); jwt.setJti("id-token"); jwt.setAud("client-id"); jwt.setSub("id-subject"); jwt.setScope("openid"); Client client = new Client(); client.setId("client-id"); client.setClientId("client-id"); router.route().order(-1) .handler(BodyHandler.create()) .handler(createOAuth2AuthHandler(oAuth2AuthProvider(jwt, client))); when(userService.findById(anyString())).thenReturn(Maybe.just(user)); testRequest( HttpMethod.POST, "/userinfo", req -> { final String body = "access_token=test-token"; req.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); req.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length())); req.write(Buffer.buffer(body)); }, HttpStatusCode.OK_200, "OK", null); }
Example #28
Source File: UserInfoEndpointHandlerTest.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
@Test public void shouldNotInvokeUserEndpoint_invalidToken_jwtDecode_post() throws Exception { router.route().order(-1) .handler(BodyHandler.create()) .handler(createOAuth2AuthHandler(oAuth2AuthProvider(new ServerErrorException()))); testRequest( HttpMethod.POST, "/userinfo", req -> { final String body = "access_token=test-token"; req.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED); req.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length())); req.write(Buffer.buffer(body)); }, HttpStatusCode.BAD_REQUEST_400, "Bad Request", null); }
Example #29
Source File: RxWebTestBase.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
protected static Buffer normalizeLineEndingsFor(Buffer buff) { int buffLen = buff.length(); Buffer normalized = Buffer.buffer(buffLen); for (int i = 0; i < buffLen; i++) { short unsignedByte = buff.getUnsignedByte(i); if (unsignedByte != '\r' || i + 1 == buffLen || buff.getUnsignedByte(i + 1) != '\n') { normalized.appendUnsignedByte(unsignedByte); } } return normalized; }
Example #30
Source File: RxWebTestBase.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
protected void testRequestBuffer(HttpClient client, HttpMethod method, int port, String path, Consumer<HttpClientRequest> requestAction, Consumer<HttpClientResponse> responseAction, int statusCode, String statusMessage, Buffer responseBodyBuffer, boolean normalizeLineEndings) throws Exception { CountDownLatch latch = new CountDownLatch(1); HttpClientRequest req = client.request(method, port, "localhost", path, resp -> { assertEquals(statusCode, resp.statusCode()); assertEquals(statusMessage, resp.statusMessage()); if (responseAction != null) { responseAction.accept(resp); } if (responseBodyBuffer == null) { latch.countDown(); } else { resp.bodyHandler(buff -> { if (normalizeLineEndings) { buff = normalizeLineEndingsFor(buff); } assertEquals(responseBodyBuffer, buff); latch.countDown(); }); } }); if (requestAction != null) { requestAction.accept(req); } req.end(); awaitLatch(latch); }