Java Code Examples for io.vertx.core.buffer.Buffer#getBytes()

The following examples show how to use io.vertx.core.buffer.Buffer#getBytes() . 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: ServiceExceptionMessageCodec.java    From vertx-service-proxy with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceException decodeFromWire(int pos, Buffer buffer) {
  int failureCode = buffer.getInt(pos);
  pos += 4;
  boolean isNull = buffer.getByte(pos) == (byte)0;
  pos++;
  String message;
  if (!isNull) {
    int strLength = buffer.getInt(pos);
    pos += 4;
    byte[] bytes = buffer.getBytes(pos, pos + strLength);
    message = new String(bytes, CharsetUtil.UTF_8);
    pos += strLength;
  } else {
    message = null;
  }
  JsonObject debugInfo = new JsonObject();
  debugInfo.readFromBuffer(pos, buffer);
  return new ServiceException(failureCode, message, debugInfo);
}
 
Example 2
Source File: KerasDl4jHandler.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
protected File getTmpFileWithContext(RoutingContext req) {
    File tmpFile = new File(UUID.randomUUID().toString());
    Buffer buff = req.getBody();
    tmpFile.deleteOnExit();
    try {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buff.getBytes());
        FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
        IOUtils.copy(byteArrayInputStream, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (IOException e) {
        tmpFile.delete();
        req.response().setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        req.response().setStatusMessage(e.getMessage());
        return null;
    }

    return tmpFile;
}
 
Example 3
Source File: TensorflowSameDiffHandler.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
protected File getTmpFileWithContext(RoutingContext req) {
    File tmpFile = new File(UUID.randomUUID().toString());
    Buffer buff = req.getBody();
    tmpFile.deleteOnExit();
    try {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buff.getBytes());
        FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
        IOUtils.copy(byteArrayInputStream, fileOutputStream);
        fileOutputStream.flush();
        fileOutputStream.close();
    } catch (IOException e) {
        tmpFile.delete();
        req.response().setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        req.response().setStatusMessage(e.getMessage());
        return null;
    }

    return tmpFile;
}
 
Example 4
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testMailSimpleSimpleNonFileAttachmentStreamCacheInFile(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  Buffer fakeData = fakeStreamData();
  byte[] fakeDataBytes = fakeData.getBytes();
  ReadStream<Buffer> fakeStream = new FakeReadStream(vertx.getOrCreateContext());
  MailAttachment attachment = MailAttachment.create().setName("FakeStream")
    .setStream(fakeStream)
    .setSize(fakeDataBytes.length);
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.SIMPLE).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(fakeDataBytes, inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 5
Source File: Pac4jUser.java    From vertx-pac4j with Apache License 2.0 6 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
    int posLocal = super.readFromBuffer(pos, buffer);
    final int jsonByteCount = buffer.getInt(posLocal);
    posLocal += 4;
    final byte[] jsonBytes = buffer.getBytes(posLocal, posLocal + jsonByteCount);
    posLocal += jsonByteCount;

    final String json = new String(jsonBytes, StandardCharsets.UTF_8);
    final JsonObject profiles = new JsonObject(json);

    final Map<String, CommonProfile> decodedUserProfiles = profiles.stream()
            .filter(e -> e.getValue() instanceof JsonObject)
            .map(e -> new MappedPair<>(e.getKey(),
                    (CommonProfile) DefaultJsonConverter.getInstance().decodeObject(e.getValue())))
            .collect(toMap(e -> e.key, e -> e.value));

    setUserProfiles(decodedUserProfiles);
    return posLocal;
}
 
Example 6
Source File: MailWithDKIMSignTest.java    From vertx-mail-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testMailSimpleSimpleNonFileAttachmentStreamCacheInFileWithLimit(TestContext testContext) {
  System.setProperty("vertx.mail.attachment.cache.file", "true");
  this.testContext = testContext;
  Buffer fakeData = fakeStreamData();
  byte[] fakeDataBytes = fakeData.getBytes();
  ReadStream<Buffer> fakeStream = new FakeReadStream(vertx.getOrCreateContext());
  MailAttachment attachment = MailAttachment.create().setName("FakeStream")
    .setStream(fakeStream)
    .setSize(fakeDataBytes.length);
  MailMessage message = exampleMessage().setText(TEXT_BODY).setAttachment(attachment);

  DKIMSignOptions dkimOps = new DKIMSignOptions(dkimOptionsBase).setBodyLimit(50)
    .setHeaderCanonAlgo(CanonicalizationAlgorithm.SIMPLE).setBodyCanonAlgo(CanonicalizationAlgorithm.SIMPLE);
  testSuccess(dkimMailClient(dkimOps), message, () -> {
    final MimeMultipart multiPart = (MimeMultipart)wiser.getMessages().get(0).getMimeMessage().getContent();
    testContext.assertEquals(2, multiPart.getCount());
    testContext.assertEquals(TEXT_BODY, conv2nl(inputStreamToString(multiPart.getBodyPart(0).getInputStream())));
    testContext.assertTrue(Arrays.equals(fakeDataBytes, inputStreamToBytes(multiPart.getBodyPart(1).getInputStream())));
    testDKIMSign(dkimOps, testContext);
  });
}
 
Example 7
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Message getFakeMessage(final String to, final Buffer payload, final String subject) {

        final Message message = mock(Message.class);
        when(message.getMessageId()).thenReturn("the-message-id");
        when(message.getSubject()).thenReturn(subject);
        when(message.getAddress()).thenReturn(to);

        if (payload != null) {
            final Data data = new Data(new Binary(payload.getBytes()));
            when(message.getContentType()).thenReturn("text/plain");
            when(message.getBody()).thenReturn(data);
        }

        return message;
    }
 
Example 8
Source File: StartupContext.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Override
public InputStream getResourceAsStream(String path) {
    String relativePath = path;
    if (relativePath.startsWith("/")) {
        relativePath = relativePath.substring(1);
    }
    FileSystem fileSystem = startupContext.vertx.fileSystem();
    FileProps props = fileSystem.propsBlocking(relativePath);
    if (props != null && !props.isDirectory()) {
        Buffer buffer = fileSystem.readFileBlocking(relativePath);
        return new ByteArrayInputStream(buffer.getBytes());
    }
    return null;

}
 
Example 9
Source File: SerializationSupport.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> int readFromBuffer(int pos, Buffer buffer, Consumer<T> objectConsumer) {
    int size = buffer.getInt(pos);
    pos += 4;
    int end = pos + size;
    try (ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(buffer.getBytes(pos, end)))) {
        Object object = is.readObject();
        objectConsumer.accept((T) object);
    } catch (Exception ex) {
        logger.error("Error deserializing object", ex);
    }
    return end;
}
 
Example 10
Source File: UserHolder.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public int readFromBuffer(int pos, Buffer buffer) {
  byte b = buffer.getByte(pos++);
  if (b == (byte)1) {
    int len = buffer.getInt(pos);
    pos += 4;
    byte[] bytes = buffer.getBytes(pos, pos + len);
    pos += len;
    String className = new String(bytes, StandardCharsets.UTF_8);
    try {
      Class<?> clazz = Utils.getClassLoader().loadClass(className);
      if (!ClusterSerializable.class.isAssignableFrom(clazz)) {
        throw new ClassCastException(className + " is not ClusterSerializable");
      }
      ClusterSerializable obj = (ClusterSerializable) clazz.getDeclaredConstructor().newInstance();
      pos = obj.readFromBuffer(pos, buffer);
      synchronized (this) {
        user = (User) obj;
        context = null;
      }
    } catch (Exception e) {
      throw new VertxException(e);
    }
  } else {
    synchronized (this) {
      user = null;
      context = null;
    }
  }
  return pos;
}
 
Example 11
Source File: BufferSerializer.java    From vertx-kafka-client with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serialize(String topic, Buffer data) {
  if (data == null)
    return null;

  return data.getBytes();
}
 
Example 12
Source File: ConversionUtils.java    From vertx-hazelcast with Apache License 2.0 5 votes vote down vote up
@Override
public void writeData(ObjectDataOutput objectDataOutput) throws IOException {
  objectDataOutput.writeUTF(clusterSerializable.getClass().getName());
  Buffer buffer = Buffer.buffer();
  clusterSerializable.writeToBuffer(buffer);
  byte[] bytes = buffer.getBytes();
  objectDataOutput.writeInt(bytes.length);
  objectDataOutput.write(bytes);
}
 
Example 13
Source File: DigestEndableWriteStream.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public void end(Buffer data) {
    byte[] bytes = data.getBytes();
    for (MessageDigest md : messageDigests) {
        md.update(bytes);
    }
    delegate.end(data);
}
 
Example 14
Source File: Block.java    From sfs with Apache License 2.0 5 votes vote down vote up
public static Optional<Frame<byte[]>> decodeFrame(Buffer buffer, boolean validateChecksum) {
    int length = buffer.length();

    final byte[] frame;
    final byte[] expectedChecksum;
    try {
        int frameSize = buffer.getInt(FRAME_LENGTH_OFFSET);
        Preconditions.checkArgument(frameSize >= 0 && frameSize < length, "Frame size was %s, expected 0 to %s", frameSize, length);
        frame = buffer.getBytes(FRAME_DATA_OFFSET, FRAME_DATA_OFFSET + frameSize);
        expectedChecksum = buffer.getBytes(FRAME_HASH_OFFSET, FRAME_HASH_OFFSET + FRAME_HASH_SIZE);
    } catch (Throwable e) {
        return Optional.absent();
    }

    Frame<byte[]> f = new Frame<byte[]>(expectedChecksum, frame) {

        @Override
        public boolean isChecksumValid() {
            return Arrays.equals(expectedChecksum, checksum(frame));
        }
    };

    if (validateChecksum) {
        if (!f.isChecksumValid()) {
            Preconditions.checkState(
                    false,
                    "Checksum was %s, expected %s",
                    BaseEncoding.base64().encode(checksum(frame)),
                    BaseEncoding.base64().encode(expectedChecksum));
        }
    }

    return Optional.of(f);
}
 
Example 15
Source File: HonoReceiver.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
private void messageReceived(final Message message) {
    synchronized (lock) {
        final long sampleReceivedTime = System.currentTimeMillis();
        messageCount++;

        if (!MessageHelper.hasDataBody(message)) {
            errorCount++;
            setSampleStartIfNotSetYet(sampleReceivedTime);
            LOGGER.warn("got message with non-Data body section; increasing errorCount in batch to {}; current batch size: {}",
                    errorCount, messageCount);
            return;
        }
        final Buffer payload = MessageHelper.getPayload(message);
        final byte[] messageBody = payload.getBytes();
        bytesReceived += messageBody.length;
        final Long senderTime = getSenderTime(message, messageBody);
        if (sampler.isUseSenderTime()) {
            if (senderTime == null) {
                errorCount++;
                setSampleStartIfNotSetYet(sampleReceivedTime);
                LOGGER.warn("got message without sender time information; increasing errorCount in batch to {}; current batch size: {}",
                        errorCount, messageCount);
            } else {
                setSampleStartIfNotSetYet(senderTime); // set sample start only once when the first message is received.
                final long sampleDeliveryTime = sampleReceivedTime - senderTime;
                if (sampleDeliveryTime < 0) {
                    // means that time on sender and receiver is not in sync
                    LOGGER.debug("got negative delivery time from received sender time: {}ms", sampleDeliveryTime);
                    senderClockNotInSync = true;
                }
                totalSampleDeliveryTime += sampleDeliveryTime;
                LOGGER.trace("received message; current batch size: {}; reception timestamp: {}; delivery time: {}ms; remaining credit: {}",
                        messageCount, sampleReceivedTime, sampleDeliveryTime, messageConsumer.getRemainingCredit());
            }
        } else {
            setSampleStartIfNotSetYet(sampleReceivedTime);
            LOGGER.trace("received message; current batch size: {}; reception timestamp: {}; remaining credit: {}", 
                    messageCount, sampleReceivedTime, messageConsumer.getRemainingCredit());
        }
    }
}
 
Example 16
Source File: ResultSetAdaptor.java    From hibernate-reactive with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public byte[] getBytes(int columnIndex) {
	Buffer buffer = row.getBuffer(columnIndex);
	return (wasNull=buffer==null) ? null : buffer.getBytes();
}
 
Example 17
Source File: HttpTermServer.java    From vertx-shell with Apache License 2.0 4 votes vote down vote up
@Override
public TermServer listen(Handler<AsyncResult<Void>> listenHandler) {

  Charset charset = Charset.forName(options.getCharset());

  boolean createServer = false;
  if (router == null) {
    createServer = true;
    router = Router.router(vertx);
  }

  if (options.getAuthOptions() != null) {
    authProvider = ShellAuth.load(vertx, options.getAuthOptions());
  }

  if (options.getSockJSPath() != null && options.getSockJSHandlerOptions() != null) {
    if (authProvider != null) {
      AuthenticationHandler basicAuthHandler = BasicAuthHandler.create(authProvider);
      router.route(options.getSockJSPath()).handler(basicAuthHandler);
    }

    Buffer inputrc = Helper.loadResource(vertx.fileSystem(), options.getIntputrc());
    if (inputrc == null) {
      if (listenHandler != null) {
        listenHandler.handle(Future.failedFuture("Could not load inputrc from " + options.getIntputrc()));
      }
      return this;
    }
    Keymap keymap = new Keymap(new ByteArrayInputStream(inputrc.getBytes()));
    SockJSHandler sockJSHandler = SockJSHandler.create(vertx, options.getSockJSHandlerOptions());
    sockJSHandler.socketHandler(new SockJSTermHandlerImpl(vertx, charset, keymap).termHandler(termHandler));
    router.route(options.getSockJSPath()).handler(sockJSHandler);
  }

  if (options.getVertsShellJsResource() != null) {
    router.get("/vertxshell.js").handler(ctx -> ctx.response().putHeader("Content-Type", "application/javascript").end(options.getVertsShellJsResource()));
  }
  if (options.getTermJsResource() != null) {
    router.get("/term.js").handler(ctx -> ctx.response().putHeader("Content-Type", "application/javascript").end(options.getTermJsResource()));
  }
  if (options.getShellHtmlResource() != null) {
    router.get("/shell.html").handler(ctx -> ctx.response().putHeader("Content-Type", "text/html").end(options.getShellHtmlResource()));
  }

  if (createServer) {
    server = vertx.createHttpServer(options);
    server.requestHandler(router);
    server.listen(ar -> {
      if (listenHandler != null) {
        if (ar.succeeded()) {
          listenHandler.handle(Future.succeededFuture());
        } else {
          listenHandler.handle(Future.failedFuture(ar.cause()));
        }
      }
    });
  } else {
    if (listenHandler != null) {
      listenHandler.handle(Future.succeededFuture());
    }
  }
  return this;
}
 
Example 18
Source File: BinaryVertxMessageReaderImpl.java    From sdk-java with Apache License 2.0 4 votes vote down vote up
public BinaryVertxMessageReaderImpl(SpecVersion version, MultiMap headers, Buffer body) {
    super(version, (body != null) ? body.getBytes() : null);

    Objects.requireNonNull(headers);
    this.headers = headers;
}
 
Example 19
Source File: ClusterSerializationUtils.java    From vertx-ignite with Apache License 2.0 4 votes vote down vote up
private static ClusterSerializableValue marshal0(ClusterSerializable obj) {
  Buffer buffer = Buffer.buffer();
  obj.writeToBuffer(buffer);
  return new ClusterSerializableValue(obj.getClass().getName(), buffer.getBytes());
}
 
Example 20
Source File: ClientHandler.java    From shadowsocks-vertx with Apache License 2.0 4 votes vote down vote up
private void sendToRemote(Buffer buffer) {
    byte [] data = buffer.getBytes();
    byte [] encryptData = mCrypto.encrypt(data);
    mServerSocket.write(Buffer.buffer(encryptData));
}