Example usage for io.vertx.core.buffer Buffer length

List of usage examples for io.vertx.core.buffer Buffer length

Introduction

In this page you can find the example usage for io.vertx.core.buffer Buffer length.

Prototype

int length();

Source Link

Document

Returns the length of the buffer, measured in bytes.

Usage

From source file:co.runrightfast.vertx.core.eventbus.ProtobufMessageCodec.java

License:Apache License

@Override
public MSG decodeFromWire(final int pos, final Buffer buffer) {
    try {/*w w  w.j a v  a  2 s  .  com*/
        return (MSG) defaultInstance.getParserForType().parseFrom(buffer.getBytes(pos, buffer.length()));
    } catch (final InvalidProtocolBufferException ex) {
        throw new ApplicationException(ex);
    }
}

From source file:com.cyngn.vertx.bosun.BosunReporter.java

License:Apache License

/**
 * Send data to the bosun instance/*from  www .j a v  a  2  s .c o  m*/
 *
 * @param api the api on bosun to send to
 * @param data the json data to send
 * @param message the event bus message the request originated from
 */
private void sendData(String api, String data, Message message) {
    HttpClient client = getNextHost();

    Buffer buffer = Buffer.buffer(data.getBytes());

    client.post(api).exceptionHandler(error -> {
        sendError(message, "Got ex contacting bosun, " + error.getLocalizedMessage());
    }).handler(response -> {
        int statusCode = response.statusCode();
        // is it 2XX
        if (statusCode >= HttpResponseStatus.OK.code()
                && statusCode < HttpResponseStatus.MULTIPLE_CHOICES.code()) {
            message.reply(new JsonObject().put(RESULT_FIELD, BosunResponse.OK_MSG));
        } else {
            response.bodyHandler(responseData -> {
                sendError(message, "got non 200 response from bosun, error: " + responseData, statusCode);
            });
        }
    }).setTimeout(timeout).putHeader(HttpHeaders.CONTENT_LENGTH, buffer.length() + "")
            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString()).write(buffer).end();
}

From source file:com.cyngn.vertx.opentsdb.service.client.OpenTsDbClient.java

License:Apache License

public boolean write(Buffer metricData) {
    if (connection.writeQueueFull()) {
        logger.error(String.format("Discarding %d bytes write buffer full", metricData.length()));
        return false;
    } else if (!connected) {
        logger.error(String.format("Discarding %d bytes no connection", metricData.length()));
        return false;
    }//ww w  .j  a  va  2 s  .  c  o m
    connection.write(metricData);

    if (logger.isDebugEnabled()) {
        logger.debug(metricData);
    }
    bytesWrittenForPeriod += metricData.length();
    return true;
}

From source file:com.cyngn.vertx.opentsdb.service.MetricsProcessor.java

License:Apache License

/**
 * Given a queue of metrics to send, process the metrics into the right format and send them over a socket
 *
 * @param metrics the metrics queue to work off
 *//*w w w  . j  a v a2s  .  co m*/
public void processMetrics(LinkedBlockingQueue<String> metrics) {
    int metricCount = metrics.size();
    if (metricCount == 0) {
        return;
    }
    List<String> drainedMetrics = new ArrayList<>();

    metrics.drainTo(drainedMetrics);
    Buffer outputBuffer = Buffer.buffer();

    int senderPos = 0;
    MetricsSender currentSender = metricsSenders.get(senderPos);

    int nextRotateIndex = drainedMetrics.size() / metricsSenders.size();
    int switchInterval = nextRotateIndex + 1;

    // loop through and serialize the metrics and send them as we fill the buffer up to max buffer
    for (int i = 0; i < drainedMetrics.size(); i++) {
        // TODO ponder if one of the host is disconnected and stays that way
        if (i == nextRotateIndex) {
            // flush the current remaining data queued before moving to the next sender
            outputBuffer = write(currentSender, outputBuffer);

            senderPos++;
            currentSender = metricsSenders.get(senderPos);
            nextRotateIndex += switchInterval;
        }

        String metric = drainedMetrics.get(i);
        byte[] bytes = metric.getBytes();

        // if this would exceed the max buffer to send go ahead and pass to the sender
        if (bytes.length + outputBuffer.length() > maxBufferSizeInBytes) {
            outputBuffer = write(currentSender, outputBuffer);
        }

        outputBuffer.appendBytes(bytes);
    }

    // send whatever is left in the buffer
    if (outputBuffer.length() > 0) {
        write(currentSender, outputBuffer);
    }
}

From source file:com.dinstone.vertx.web.core.JsonMessageConverter.java

License:Apache License

@Override
public Object read(Class<? extends Object> clazz, RoutingContext context) throws IOException {
    Buffer body = context.getBody();
    if (body.length() > 0) {
        return Json.decodeValue(body, clazz);
    }/* ww  w.  j a  v a 2 s  .  co m*/
    return null;
}

From source file:com.englishtown.vertx.jersey.impl.DefaultJerseyHandler.java

License:Open Source License

/**
 * {@inheritDoc}/*from w w w  . j  ava  2  s.  c  o  m*/
 */
@Override
public void handle(final HttpServerRequest vertxRequest) {

    // Wait for the body for jersey to handle form/json/xml params
    if (shouldReadData(vertxRequest)) {
        if (logger.isDebugEnabled()) {
            logger.debug("DefaultJerseyHandler - handle request and read body: " + vertxRequest.method() + " "
                    + vertxRequest.uri());
        }
        final Buffer body = Buffer.buffer();

        vertxRequest.handler(buffer -> {
            body.appendBuffer(buffer);
            if (body.length() > maxBodySize) {
                throw new RuntimeException(
                        "The input stream has exceeded the max allowed body size " + maxBodySize + ".");
            }
        });
        vertxRequest.endHandler(aVoid -> {
            InputStream inputStream = new ByteArrayInputStream(body.getBytes());
            DefaultJerseyHandler.this.handle(vertxRequest, inputStream);
        });

    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("DefaultJerseyHandler - handle request: " + vertxRequest.method() + " "
                    + vertxRequest.uri());
        }
        DefaultJerseyHandler.this.handle(vertxRequest, null);
    }

}

From source file:com.groupon.vertx.memcache.stream.MemcacheInputStream.java

License:Apache License

/**
 * This method handles processing the incoming Buffer from the NetSocket.  The Buffer
 * is not guaranteed to contain a whole message so this method tracks the current state
 * of the incoming data and notifies the pending commands when enough data has been sent
 * for a response./*from   w  w  w.j a v a 2  s . c o  m*/
 *
 * @param processBuffer - The Buffer containing the current set of bytes.
 */
public void processBuffer(Buffer processBuffer) {
    if (processBuffer == null || processBuffer.length() == 0) {
        return;
    }

    byte first;
    byte second;

    ByteBuf byteBuf = processBuffer.getByteBuf();

    while (byteBuf.isReadable()) {
        first = byteBuf.readByte();
        if (first == '\r') {
            if (byteBuf.isReadable()) {
                second = byteBuf.readByte();
                if (second == '\n') {
                    addCompletedLine();
                }
                previous = second;
            } else {
                previous = first;
            }
        } else if (first == '\n' && previous == '\r') {
            addCompletedLine();
            previous = first;
        } else {
            buffer.write(first);
            previous = first;
        }
    }
}

From source file:com.groupon.vertx.redis.RedisInputStream.java

License:Apache License

/**
 * This method handles processing the incoming Buffer from the NetSocket.  The Buffer
 * is not guaranteed to contain a whole message so this method tracks the current state
 * of the incoming data and notifies the pending commands when enough data has been sent
 * for a response.//  w  w w .  j  a v a  2 s .  c  o m
 *
 * @param processBuffer - The Buffer containing the current set of bytes.
 */
public void processBuffer(Buffer processBuffer) {
    if (processBuffer == null || processBuffer.length() == 0) {
        return;
    }

    byte first;
    byte second;

    ByteBuf byteBuf = processBuffer.getByteBuf();

    while (byteBuf.isReadable()) {
        first = byteBuf.readByte();
        if (first == '\r' && byteBuf.isReadable()) {
            second = byteBuf.readByte();
            if (second == '\n') {
                byte[] line = new byte[bufferPosition];
                System.arraycopy(buffer, 0, line, 0, line.length);
                addCompletedLine(line);
            } else {
                buffer[bufferPosition++] = first;
                buffer[bufferPosition++] = second;
            }
        } else if (first == '\n' && buffer[bufferPosition - 1] == '\r') {
            byte[] line = new byte[bufferPosition - 1];
            System.arraycopy(buffer, 0, line, 0, line.length);
            addCompletedLine(line);
        } else {
            buffer[bufferPosition++] = first;
        }
    }
}

From source file:com.hubrick.vertx.kafka.producer.DefaultKafkaProducerService.java

License:Apache License

private boolean isValid(Buffer buffer) {
    return buffer != null && buffer.length() > 0;
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

License:Apache License

private static void logDebugResponse(Buffer buffer) {
    if (log.isDebugEnabled()) {
        if (buffer.length() > MAX_LOG_OUTPUT) {
            log.debug("Response: {}",
                    new String(buffer.getBytes(0, MAX_LOG_OUTPUT), Charsets.UTF_8) + "\nRest truncated......");
        } else {//w w  w . ja va2  s.  c o m
            log.debug("Response: {}", new String(buffer.getBytes(), Charsets.UTF_8));
        }
    }
}