Java Code Examples for io.vertx.core.buffer.Buffer

The following are top voted examples for showing how to use io.vertx.core.buffer.Buffer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: vertx-prometheus-metrics   File: MetricsProtobufHandler.java   View source code 7 votes vote down vote up
@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());
    }
  });
}
 
Example 2
Project: vertx-sfdc-platformevents   File: SoapApi.java   View source code 7 votes vote down vote up
@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");
	}
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: TcpConnection.java   View source code 6 votes vote down vote up
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));
  }
}
 
Example 4
Project: vertx-fastdfs-client   File: FdfsClientImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 5
Project: jgossip   File: GossipManager.java   View source code 6 votes vote down vote up
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);
            }
        }
    }
}
 
Example 6
Project: vertx-fastdfs-client   File: FdfsClientImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 7
Project: redpipe   File: MyResource.java   View source code 6 votes vote down vote up
@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;
}
 
Example 8
Project: redpipe   File: MyResource.java   View source code 6 votes vote down vote up
@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");
}
 
Example 9
Project: redpipe   File: MyResource.java   View source code 6 votes vote down vote up
@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();
	});
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: TestVertxServerRequestToHttpServletRequest.java   View source code 6 votes vote down vote up
@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());
}
 
Example 11
Project: metagraph-auth   File: VertxWebTest.java   View source code 6 votes vote down vote up
public void testImplicitMode() {
    vertx = Vertx.vertx();
    WebClient client = WebClient.create(vertx);
    HttpRequest<Buffer> request = client.postAbs("http://admin:[email protected]:8080/oauth/authorize?response_type=token&scope=read%20write&client_id=myClientId&redirect_uri=http://example.com");
    request.putHeader("Authorization", getHeader());
    request.send(ar -> {
        if (ar.succeeded()) {
            HttpResponse<Buffer> response = ar.result();
            //String location = response.getHeader("Location");
            String body = response.bodyAsString();
            System.out.println("Implicit Mode Get Token" + body + " status code" + response.statusCode() + " Location=");
        } else {
            System.out.println("Something went wrong " + ar.cause().getMessage());
        }
    });
}
 
Example 12
Project: incubator-servicecomb-java-chassis   File: RestBodyHandler.java   View source code 6 votes vote down vote up
@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);
    }
  }
}
 
Example 13
Project: redpipe   File: MyResource.java   View source code 6 votes vote down vote up
@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();
	});
}
 
Example 14
Project: vertx-sfdc-platformevents   File: RestConsumer.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 15
Project: reactive-pg-client   File: ArrayTuple.java   View source code 6 votes vote down vote up
@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;
}
 
Example 16
Project: jgossip   File: GossipManager.java   View source code 6 votes vote down vote up
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;
}
 
Example 17
Project: vertx-sfdc-platformevents   File: CometD.java   View source code 6 votes vote down vote up
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());
		}
	});
}
 
Example 18
Project: vertx-fastdfs-client   File: FdfsClientImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 19
Project: incubator-servicecomb-java-chassis   File: TestHighwayCodec.java   View source code 6 votes vote down vote up
@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);
}
 
Example 20
Project: app-ms   File: VertxTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 21
Project: vertx-aws-lambda   File: HttpServerResponseImpl.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 22
Project: vertx-fastdfs-client   File: FdfsClientImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 23
Project: jgossip   File: AckMessageHandler.java   View source code 6 votes vote down vote up
@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);
        }
    }
}
 
Example 24
Project: incubator-servicecomb-java-chassis   File: TestAbstractRestInvocation.java   View source code 6 votes vote down vote up
@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());
}
 
Example 25
Project: vertx-fastdfs-client   File: FdfsStorageImpl.java   View source code 5 votes vote down vote up
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;
}
 
Example 26
Project: vertx-sfdc-platformevents   File: RestConsumer.java   View source code 5 votes vote down vote up
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;
}
 
Example 27
Project: vertx-acme4j   File: PemLoader.java   View source code 5 votes vote down vote up
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;
}
 
Example 28
Project: metagraph-auth   File: VertxWebTest.java   View source code 5 votes vote down vote up
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());
        }
    });
}
 
Example 29
Project: vertx-corenlp-client   File: CoreNLPClientImpl.java   View source code 5 votes vote down vote up
@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()));
      }
    });
}
 
Example 30
Project: vertx-aws-lambda   File: HttpServerResponseImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 31
Project: vertx-aws-lambda   File: HttpServerRequestImplTest.java   View source code 5 votes vote down vote up
@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")));
}
 
Example 32
Project: app-ms   File: VertxOutputStream.java   View source code 5 votes vote down vote up
@Override
public void write(final int b) throws IOException {

    checkClosed();
    addChunkedIfNeeded();
    final Buffer buffer = buffer(new byte[] {
        (byte) b
    });
    stream.write(buffer);

}
 
Example 33
Project: incubator-servicecomb-java-chassis   File: TestBodyBufferSupportImpl.java   View source code 5 votes vote down vote up
@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());
}
 
Example 34
Project: incubator-servicecomb-java-chassis   File: TestStandardHttpServletRequestEx.java   View source code 5 votes vote down vote up
@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()));
}
 
Example 35
Project: vertx-fastdfs-client   File: FdfsStorageImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 36
Project: incubator-servicecomb-java-chassis   File: TestStandardHttpServletResponseEx.java   View source code 5 votes vote down vote up
@Test
public void getBodyBytes() {
  Buffer bodyBuffer = Buffer.buffer();
  bodyBuffer.appendString("abc");
  responseEx.setBodyBuffer(bodyBuffer);
  Assert.assertEquals("abc", new String(responseEx.getBodyBytes(), 0, responseEx.getBodyBytesLength()));
}
 
Example 37
Project: incubator-servicecomb-java-chassis   File: TestTcpParser.java   View source code 5 votes vote down vote up
@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());
}
 
Example 38
Project: vertx-fastdfs-client   File: FdfsClientImpl.java   View source code 5 votes vote down vote up
@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;
}
 
Example 39
Project: metagraph-auth   File: VertxWebTest.java   View source code 5 votes vote down vote up
public void testAuthorizationCode() {
    vertx = Vertx.vertx();
    WebClient client = WebClient.create(vertx);
    HttpRequest<Buffer> request = client.postAbs("http://admin:[email protected]:8080/oauth/authorize?client_id=myClientId&client_secret=myClientSecret&redirect_uri=http://example.com&response_type=code&scope=read%20write");
    request.putHeader("Authorization", getHeader());
    request.send(ar -> {
        if (ar.succeeded()) {
            HttpResponse<Buffer> response = ar.result();
            String body = response.bodyAsString();
            System.out.println("Authorization Code Mode Get Token" + body + " status code" + response.statusCode());
        } else {
            System.out.println("Something went wrong " + ar.cause().getMessage());
        }
    });
}
 
Example 40
Project: incubator-servicecomb-java-chassis   File: HighwayServerInvoke.java   View source code 5 votes vote down vote up
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;
}