@Override public void handle(@NotNull RoutingContext context) { context.vertx().<Buffer>executeBlocking(future -> { try (final ByteArrayOutputStream output = new ByteArrayOutputStream()) { new ProtobufFormatter(registry.metricFamilySamples()).write(output); future.complete(Buffer.buffer(output.toByteArray())); } catch (IOException e) { future.fail(e); } }, false, result -> { if (result.succeeded()) { context.response() .setStatusCode(HttpResponseStatus.OK.code()) .putHeader("Content-Type", ProtobufFormatter.CONTENT_TYPE) .end(result.result()); } else { context.fail(result.cause()); } }); }
@Override protected void login(final Future<AuthInfo> futureAuthinfo) { final WebClientOptions wco = new WebClientOptions(); final String proxyHost = this.getAuthConfig().getProxy(); final int proxyPort = this.getAuthConfig().getProxyPort(); if ((proxyHost != null) && (proxyPort > 0)) { final ProxyOptions po = new ProxyOptions(); wco.setProxyOptions(po); po.setHost(proxyHost).setPort(proxyPort); } wco.setUserAgent("SDFC VertX Authenticator"); wco.setTryUseCompression(true); final WebClient authClient = WebClient.create(this.vertx, wco); final Buffer body = this.getAuthBody(this.getAuthConfig().getSfdcUser(), this.getAuthConfig().getSfdcPassword()); if (!this.shuttingDown && !this.shutdownCompleted) { authClient.post(Constants.TLS_PORT, this.getAuthConfig().getServerURL(), Constants.AUTH_SOAP_LOGIN) .putHeader("Content-Type", "text/xml").ssl(true).putHeader("SOAPAction", "Login") .putHeader("PrettyPrint", "Yes").sendBuffer(body, postReturn -> { this.resultOfAuthentication(postReturn, futureAuthinfo); }); } else { this.shutdownCompleted = true; futureAuthinfo.fail("Auth disruped by stop command"); } }
protected void writeInContext() { CompositeByteBuf cbb = ByteBufAllocator.DEFAULT.compositeBuffer(); for (;;) { ByteBuf buf = writeQueue.poll(); if (buf == null) { break; } writeQueueSize.decrementAndGet(); cbb.addComponent(true, buf); if (cbb.numComponents() == cbb.maxNumComponents()) { netSocket.write(Buffer.buffer(cbb)); cbb = ByteBufAllocator.DEFAULT.compositeBuffer(); } } if (cbb.isReadable()) { netSocket.write(Buffer.buffer(cbb)); } }
@Override public FdfsClient download(FdfsFileId fileId, long offset, long bytes, Handler<AsyncResult<Buffer>> handler) { getTracker().setHandler(tracker -> { if (tracker.succeeded()) { tracker.result().getFetchStorage(fileId, storage -> { if (storage.succeeded()) { storage.result().download(fileId, offset, bytes, download -> { handler.handle(download); }); } else { handler.handle(Future.failedFuture(storage.cause())); } }); } else { handler.handle(Future.failedFuture(tracker.cause())); } }); return this; }
private void gossip2Seed(Buffer buffer) { int size = settings.getSeedMembers().size(); if (size > 0) { if (size == 1 && settings.getSeedMembers().contains(gossipMember2SeedMember(getSelf()))) { return; } int index = (size == 1) ? 0 : random.nextInt(size); if (liveMembers.size() == 1) { sendGossip2Seed(buffer, settings.getSeedMembers(), index); } else { double prob = size / Double.valueOf(liveMembers.size()); ; if (random.nextDouble() < prob) { sendGossip2Seed(buffer, settings.getSeedMembers(), index); } } } }
@Override public FdfsClient modify(Buffer buffer, FdfsFileId fileId, long offset, Handler<AsyncResult<Void>> handler) { getTracker().setHandler(tracker -> { if (tracker.succeeded()) { tracker.result().getStoreStorage(fileId.group(), storage -> { if (storage.succeeded()) { storage.result().modify(buffer, fileId, offset, modify -> { handler.handle(modify); }); } else { handler.handle(Future.failedFuture(storage.cause())); } }); } else { handler.handle(Future.failedFuture(tracker.cause())); } }); return this; }
@Path("7error") @GET public CompletionStage<String> hello7Error(@Context Vertx vertx){ io.vertx.rxjava.core.Vertx rxVertx = io.vertx.rxjava.core.Vertx.newInstance(vertx); System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.rxjava.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); CompletableFuture<String> ret = new CompletableFuture<>(); responseHandler.subscribe(body -> { System.err.println("Got body"); ret.completeExceptionally(new MyException()); }); System.err.println("Created client"); return ret; }
@Path("6") @GET public void hello6(@Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx){ io.vertx.rxjava.core.Vertx rxVertx = io.vertx.rxjava.core.Vertx.newInstance(vertx); System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.rxjava.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); responseHandler.subscribe(body -> { System.err.println("Got body"); asyncResponse.resume(Response.ok(body.body().toString()).build()); }); System.err.println("Created client"); }
@Path("coroutines/1") @GET public Single<Response> helloAsync(@Context io.vertx.rxjava.core.Vertx rxVertx){ return Fibers.fiber(() -> { System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.rxjava.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); System.err.println("Got response"); HttpResponse<io.vertx.rxjava.core.buffer.Buffer> httpResponse = Fibers.await(responseHandler); System.err.println("Got body"); return Response.ok(httpResponse.body().toString()).build(); }); }
@Test public void setBodyBuffer() { Holder<Buffer> bodyHolder = new Holder<>(); context = new MockUp<RoutingContext>() { @Mock HttpServerRequest request() { return vertxRequest; } @Mock void setBody(Buffer body) { bodyHolder.value = body; } }.getMockInstance(); request = new VertxServerRequestToHttpServletRequest(context); Buffer bodyBuffer = Buffer.buffer(); request.setBodyBuffer(bodyBuffer); Assert.assertSame(bodyBuffer, bodyHolder.value); Assert.assertSame(bodyBuffer, request.getBodyBuffer()); }
@Override public void handle(Buffer buff) { if (failed) { return; } uploadSize += buff.length(); if (bodyLimit != -1 && uploadSize > bodyLimit) { failed = true; context.fail(Status.REQUEST_ENTITY_TOO_LARGE.getStatusCode()); } else { // multipart requests will not end up in the request body // url encoded should also not, however jQuery by default // post in urlencoded even if the payload is something else if (!isMultipart /* && !isUrlEncoded */) { body.appendBuffer(buff); } } }
@Path("8") @GET public Single<String> hello8(@Context io.vertx.rxjava.core.Vertx rxVertx){ System.err.println("Creating client"); WebClientOptions options = new WebClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); WebClient client = WebClient.create(rxVertx, options); Single<HttpResponse<io.vertx.rxjava.core.buffer.Buffer>> responseHandler = client.get(443, "www.google.com", "/robots.txt").rxSend(); System.err.println("Created client"); return responseHandler.map(body -> { System.err.println("Got body"); return body.body().toString(); }); }
/** * Turns the JsonObject that came over the wire into a buffer object to be * used in the HTTP Post. Special twist: if configured the JSONObject is run * through a {{Mustache}} transformation, so the result can be anything * JSON, HTML, XML, PlainText, WebForm etc. Allows ultimate flexibility when * one knows Mustache * * @param Json * Object with incoming payload * @return a Buffer object to be pasted */ private Buffer transformBody(final JsonObject body) { Buffer result = null; if (this.needsTransformation()) { final Mustache mustache = this.getMustache(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintWriter pw = new PrintWriter(out); try { mustache.execute(pw, Utils.mappifyJsonObject(body)).flush(); pw.close(); result = Buffer.buffer(out.toByteArray()); } catch (final IOException e) { this.logger.error(e); // Get back the unchanged body result = body.toBuffer(); } } else { result = body.toBuffer(); } return result; }
@Override public Tuple addValue(Object value) { if(value instanceof Boolean || value instanceof Number || value instanceof Character || value instanceof String || value instanceof JsonObject || value instanceof JsonArray || value instanceof Buffer || value instanceof LocalTime || value instanceof OffsetTime || value instanceof LocalDate || value instanceof LocalDateTime || value instanceof OffsetDateTime) { add(value); } else { add(null); } return this; }
private boolean sendGossip(Buffer buffer, List<GossipMember> members, int index) { if (buffer != null && index >= 0) { try { GossipMember target = members.get(index); if (target.equals(getSelf())) { int m_size = members.size(); if (m_size == 1) { return false; } else { target = members.get((index + 1) % m_size); } } settings.getMsgService().sendMsg(target.getIpAddress(), target.getPort(), buffer); return settings.getSeedMembers().contains(gossipMember2SeedMember(target)); } catch (Exception e) { LOGGER.error(e.getMessage()); } } return false; }
private void step3ActionAdvice(final JsonObject handshakeResult) { if (this.shuttingDown || this.shutdownCompleted) { this.shutdownCompleted = true; return; } final JsonArray body = this.getAdviceBody(); final HttpRequest<Buffer> request = this.initWebPostRequest(Constants.URL_CONNECT); request.sendJson(body, postReturn -> { if (postReturn.succeeded()) { this.step3ResultAdvice(postReturn.result()); } else { this.logger.error(postReturn.cause()); } }); }
@Override public FdfsClient append(Buffer buffer, FdfsFileId fileId, Handler<AsyncResult<Void>> handler) { getTracker().setHandler(tracker -> { if (tracker.succeeded()) { tracker.result().getStoreStorage(fileId.group(), storage -> { if (storage.succeeded()) { storage.result().append(buffer, fileId, append -> { handler.handle(append); }); } else { handler.handle(Future.failedFuture(storage.cause())); } }); } else { handler.handle(Future.failedFuture(tracker.cause())); } }); return this; }
@Test public void testReadRequestHeader() { boolean status = true; try { new MockUp<NotWrapSchema>() { @Mock public Object readObject(Input input) throws IOException { return new RequestHeader(); } }; bodyBuffer = Buffer.buffer("\"abc\""); RequestHeader requestHeader = HighwayCodec.readRequestHeader(bodyBuffer, null); Assert.assertNotNull(requestHeader); Assert.assertEquals(0, requestHeader.getFlags()); } catch (Exception e) { status = false; } Assert.assertTrue(status); }
@Test public void testManifestRouteText(final TestContext context) { final Router router = Router.router(rule.vertx()); final ManifestHandler handler = ManifestHandler.registerToRouter(router); final RoutingContext routingContext = mock(RoutingContext.class); when(routingContext.currentRoute()).thenReturn(router.get("/.well-known/manifest")); when(routingContext.request()).thenReturn(mock(HttpServerRequest.class)); when(routingContext.getAcceptableContentType()).thenReturn(MediaType.TEXT_PLAIN); final HttpServerResponse response = mock(HttpServerResponse.class); when(response.putHeader(anyString(), anyString())).thenReturn(response); when(routingContext.response()).thenReturn(response); handler.handle(routingContext); verify(response, times(1)).end(any(Buffer.class)); }
@Override public void end(Buffer chunk) { checkWritten(); if (!chunked && !contentLengthSet()) { headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(chunk.length())); } body().appendBuffer(chunk); if (!headWritten) { prepareHeaders(); } outputResponse(); closed = true; written = true; if (bodyEndHandler != null) { bodyEndHandler.handle(null); } if (endHandler != null) { endHandler.handle(null); } }
@Override public FdfsClient download(FdfsFileId fileId, WriteStream<Buffer> stream, long offset, long bytes, Handler<AsyncResult<Void>> handler) { getTracker().setHandler(tracker -> { if (tracker.succeeded()) { tracker.result().getFetchStorage(fileId, storage -> { if (storage.succeeded()) { storage.result().download(fileId, stream, offset, bytes, download -> { handler.handle(download); }); } else { handler.handle(Future.failedFuture(storage.cause())); } }); } else { handler.handle(Future.failedFuture(tracker.cause())); } }); return this; }
@Override public void handle(String cluster, String data, String from) { JsonObject dj = new JsonObject(data); AckMessage ackMessage = dj.mapTo(AckMessage.class); List<GossipDigest> olders = ackMessage.getOlders(); Map<GossipMember, HeartbeatState> newers = ackMessage.getNewers(); //update local state if (newers.size() > 0) { GossipManager.getInstance().apply2LocalState(newers); } Map<GossipMember, HeartbeatState> deltaEndpoints = new HashMap<>(); if (olders != null) { for (GossipDigest d : olders) { GossipMember member = GossipManager.getInstance().createByDigest(d); HeartbeatState hb = GossipManager.getInstance().getEndpointMembers().get(member); if (hb != null) { deltaEndpoints.put(member, hb); } } } if (!deltaEndpoints.isEmpty()) { Ack2Message ack2Message = new Ack2Message(deltaEndpoints); Buffer ack2Buffer = GossipManager.getInstance().encodeAck2Message(ack2Message); if (from != null) { String[] host = from.split(":"); GossipManager.getInstance().getSettings().getMsgService().sendMsg(host[0], Integer.valueOf(host[1]), ack2Buffer); } } }
@Test public void testDoSendResponseResultOK(@Mocked Response response) throws Exception { new Expectations() { { response.getResult(); result = "ok"; } }; Buffer buffer = Buffer.buffer(); responseEx = new MockUp<HttpServletResponseEx>() { @Mock void setBodyBuffer(Buffer bodyBuffer) { buffer.appendBuffer(bodyBuffer); } }.getMockInstance(); initRestInvocation(); restInvocation.sendResponse(response); Assert.assertEquals("\"ok\"", buffer.toString()); }
private Future<FdfsFileId> uploadFile(byte command, String fileFullPathName, String ext) { Buffer extBuffer = Buffer.buffer(ext, options.getCharset()); if (extBuffer.length() > FdfsProtocol.FDFS_FILE_EXT_NAME_MAX_LEN) { return Future.failedFuture("ext is too long ( greater than " + FdfsProtocol.FDFS_FILE_EXT_NAME_MAX_LEN + ")"); } Future<FdfsFileId> futureFileId = Future.future(); LocalFile.readFile(vertx.fileSystem(), fileFullPathName).setHandler(ar -> { if (ar.succeeded()) { LocalFile localFile = ar.result(); uploadFile(command, localFile.getFile(), localFile.getSize(), ext).setHandler(upload -> { localFile.closeFile(); if (upload.succeeded()) { futureFileId.complete(upload.result()); } else { futureFileId.fail(upload.cause()); } }); } else { futureFileId.fail(ar.cause()); } }); return futureFileId; }
private HttpRequest<Buffer> initWebPostRequest(final String destination) { final WebClient client = this.initWebClient(); final HttpRequest<Buffer> request = client.post(destination).ssl(true) .putHeader(Constants.AUTH_HEADER, this.authInfo.sessionToken) .putHeader(Constants.CONTENT_HEADER, this.getContentType()); return request; }
private static List<byte[]> loadPem(Buffer data, String delimiter) throws IOException { String pem = data.toString(); String beginDelimiter = "-----BEGIN " + delimiter + "-----"; String endDelimiter = "-----END " + delimiter + "-----"; List<byte[]> pems = new ArrayList<>(); int index = 0; while (true) { index = pem.indexOf(beginDelimiter, index); if (index == -1) { break; } index += beginDelimiter.length(); int end = pem.indexOf(endDelimiter, index); if (end == -1) { throw new RuntimeException("Missing " + endDelimiter + " delimiter"); } String content = pem.substring(index, end); content = content.replaceAll("\\s", ""); if (content.length() == 0) { throw new RuntimeException("Empty pem file"); } index = end + 1; pems.add(Base64.getDecoder().decode(content)); } if (pems.isEmpty()) { throw new RuntimeException("Missing " + beginDelimiter + " delimiter"); } return pems; }
public void testPasswordMode() { vertx = Vertx.vertx(); WebClient client = WebClient.create(vertx); HttpRequest<Buffer> request = client.postAbs("http://localhost:8080/oauth/token?client_id=myClientId&client_secret=myClientSecret&grant_type=password&username=admin&password=admin"); request.send(ar -> { if (ar.succeeded()) { HttpResponse<Buffer> response = ar.result(); JsonObject body = response.bodyAsJsonObject(); System.out.println("Password Mode Get Token" + body + " status code" + response.statusCode()); } else { System.out.println("Something went wrong " + ar.cause().getMessage()); } }); }
@Override public void semgrex(RequestParameters parameters, Handler<AsyncResult<JsonObject>> handler) { Objects.requireNonNull(parameters.getPattern(), "pattern must have a value"); buildRequest("/semgrex", parameters) .sendBuffer(Buffer.buffer(parameters.getText()), h -> { if (h.succeeded()) { handler.handle(Future.succeededFuture(h.result().body())); } else { handler.handle(Future.failedFuture(h.cause())); } }); }
@Override public HttpServerResponse write(Buffer data) { checkWritten(); if (!headWritten && !chunked && !contentLengthSet()) { throw new IllegalStateException( "You must set the Content-Length header to be the total size of the message " + "body BEFORE sending any data if you are not using HTTP chunked encoding."); } if (!headWritten) { prepareHeaders(); } body().appendBuffer(data); return this; }
@Test public void testEndHandler(TestContext context) { context.assertEquals(request, request.endHandler(ar -> { request.response().end("data1"); })); request.handleEnd(); context.assertEquals("data1", new String(new JsonObject(Buffer.buffer(responseOutput.toByteArray())).getBinary("body"))); }
@Override public void write(final int b) throws IOException { checkClosed(); addChunkedIfNeeded(); final Buffer buffer = buffer(new byte[] { (byte) b }); stream.write(buffer); }
@Test public void testGetBodyBytesLength() { Assert.assertEquals(0, impl.getBodyBytesLength()); byte[] bytes = new byte[] {1, 2, 3}; Buffer bodyBuffer = Buffer.buffer(bytes); impl.setBodyBuffer(bodyBuffer); Assert.assertEquals(3, impl.getBodyBytesLength()); }
@Test public void setBodyBuffer() { Buffer bodyBuffer = Buffer.buffer(); bodyBuffer.appendString("abc"); requestEx.setBodyBuffer(bodyBuffer); Assert.assertSame(bodyBuffer, requestEx.getBodyBuffer()); Assert.assertArrayEquals("abc".getBytes(), Arrays.copyOf(requestEx.getBodyBytes(), requestEx.getBodyBytesLength())); }
@Override public FdfsStorage delete(FdfsFileId fileId, Handler<AsyncResult<Void>> handler) { Future<FdfsConnection> futureConn = getConnection(); futureConn.compose(connection -> { Future<FdfsPacket> futureResponse = FdfsProtocol.recvPacket(vertx, options.getNetworkTimeout(), connection, FdfsProtocol.STORAGE_PROTO_CMD_RESP, 0, null); Buffer packet = FdfsProtocol.packFileId(FdfsProtocol.STORAGE_PROTO_CMD_DELETE_FILE, fileId, options.getCharset()); connection.write(packet); if (connection.writeQueueFull()) { connection.pause(); connection.drainHandler(v -> { connection.resume(); }); } return futureResponse; }).setHandler(ar -> { if (futureConn.succeeded()) { futureConn.result().release(); } if (ar.succeeded()) { handler.handle(Future.succeededFuture()); } else { handler.handle(Future.failedFuture(ar.cause())); } }); return this; }
@Test public void getBodyBytes() { Buffer bodyBuffer = Buffer.buffer(); bodyBuffer.appendString("abc"); responseEx.setBodyBuffer(bodyBuffer); Assert.assertEquals("abc", new String(responseEx.getBodyBytes(), 0, responseEx.getBodyBytesLength())); }
@Test public void test() throws UnsupportedEncodingException { TcpBufferHandler output = new TcpBufferHandler() { @Override public void handle(long _msgId, Buffer _headerBuffer, Buffer _bodyBuffer) { msgId = _msgId; headerBuffer = _headerBuffer; bodyBuffer = _bodyBuffer; } }; byte[] header = new byte[] {1, 2, 3}; byte[] body = new byte[] {1, 2, 3, 4}; TcpOutputStream os = new TcpOutputStream(1); os.writeInt(header.length + body.length); os.writeInt(header.length); os.write(header); os.write(body); TcpParser parser = new TcpParser(output); parser.handle(os.getBuffer()); os.close(); Assert.assertEquals(1, msgId); Assert.assertArrayEquals(header, headerBuffer.getBytes()); Assert.assertArrayEquals(body, bodyBuffer.getBytes()); }
@Override public FdfsClient upload(Buffer buffer, String ext, Handler<AsyncResult<FdfsFileId>> handler) { if (Buffer.buffer(ext, options.getCharset()).length() > FdfsProtocol.FDFS_FILE_EXT_NAME_MAX_LEN) { handler.handle(Future .failedFuture("ext is too long ( greater than " + FdfsProtocol.FDFS_FILE_EXT_NAME_MAX_LEN + ")")); return this; } getTracker().setHandler(tracker -> { if (tracker.succeeded()) { tracker.result().getStoreStorage(storage -> { if (storage.succeeded()) { storage.result().upload(buffer, ext, upload -> { handler.handle(upload); }); } else { handler.handle(Future.failedFuture(storage.cause())); } }); } else { handler.handle(Future.failedFuture(tracker.cause())); } }); return this; }
private void doInit(TcpConnection connection, long msgId, RequestHeader header, Buffer bodyBuffer) throws Exception { this.connection = connection; this.msgId = msgId; this.header = header; MicroserviceMeta microserviceMeta = microserviceMetaManager.ensureFindValue(header.getDestMicroservice()); SchemaMeta schemaMeta = microserviceMeta.ensureFindSchemaMeta(header.getSchemaId()); this.operationMeta = schemaMeta.ensureFindOperation(header.getOperationName()); this.operationProtobuf = ProtobufManager.getOrCreateOperation(operationMeta); this.bodyBuffer = bodyBuffer; }