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

The following examples show how to use io.vertx.core.buffer.Buffer#length() . 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: JmsBasedDeviceConnectionClient.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected RequestResponseResult<JsonObject> getResult(final int status, final Buffer payload, final CacheDirective cacheDirective) {

    if (payload == null || payload.length() == 0) {
        return new RequestResponseResult<>(status, null, null, null);
    } else {
        try {
            final JsonObject json = payload.toJsonObject();
            return new RequestResponseResult<>(status, json, null, null);
        } catch (final DecodeException e) {
            LOGGER.warn("Device Connection service returned malformed payload", e);
            throw new ServiceInvocationException(
                    HttpURLConnection.HTTP_INTERNAL_ERROR,
                    "Device Connection service returned malformed payload");
        }
    }
}
 
Example 2
Source File: EventSourceTransport.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public void sendFrame(String body, Handler<AsyncResult<Void>> handler) {
  if (log.isTraceEnabled()) log.trace("EventSource, sending frame");
  if (!headersWritten) {
    // event stream data is always UTF8
    // https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format
    // no need to specify the character encoding
    rc.response().putHeader(HttpHeaders.CONTENT_TYPE, "text/event-stream");
    setNoCacheHeaders(rc);
    setJSESSIONID(options, rc);
    rc.response().setChunked(true).write("\r\n");
    headersWritten = true;
  }
  String sb = "data: " +
    body +
    "\r\n\r\n";
  Buffer buff = buffer(sb);
  rc.response().write(buff, handler);
  bytesSent += buff.length();
  if (bytesSent >= maxBytesStreaming) {
    if (log.isTraceEnabled()) log.trace("More than maxBytes sent so closing connection");
    // Reset and close the connection
    close();
  }
}
 
Example 3
Source File: RestBodyHandler.java    From servicecomb-java-chassis with Apache License 2.0 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;
    // enqueue a delete for the error uploads
    context.fail(new InvocationException(Status.REQUEST_ENTITY_TOO_LARGE,
        Status.REQUEST_ENTITY_TOO_LARGE.getReasonPhrase()));
    context.vertx().runOnContext(v -> deleteFileUploads());
  } 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 4
Source File: BlockFile.java    From sfs with Apache License 2.0 6 votes vote down vote up
private Observable<Void> setBlock0(SfsVertx vertx, final long position, Buffer data) {
    Context context = vertx.getOrCreateContext();
    long length = data.length();
    // this should never happen but in case things ever get crazy this will prevent corruption
    checkState(length <= blockSize, "Frame size was %s, expected %s", length, blockSize);
    ObservableFuture<Void> drainHandler = RxHelper.observableFuture();
    if (writeQueueSupport.writeQueueFull()) {
        writeQueueSupport.drainHandler(context, drainHandler::complete);
    } else {
        drainHandler.complete(null);
    }
    return drainHandler.flatMap(aVoid ->
            using(
                    () -> {
                        AsyncFileWriter writer = createWriteStream(context, position);
                        activeWriters.add(writer);
                        return writer;
                    },
                    writer ->
                            end(data, writer)
                                    .doOnNext(aVoid1 -> activeWriters.remove(writer)),
                    activeWriters::remove));
}
 
Example 5
Source File: BufferWrappingBytes.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
BufferWrappingBytes(Buffer buffer, int offset, int length) {
  checkArgument(length >= 0, "Invalid negative length");
  int bufferLength = buffer.length();
  checkElementIndex(offset, bufferLength + 1);
  checkArgument(
      offset + length <= bufferLength,
      "Provided length %s is too big: the buffer has size %s and has only %s bytes from %s",
      length,
      bufferLength,
      bufferLength - offset,
      offset);

  if (offset == 0 && length == bufferLength) {
    this.buffer = buffer;
  } else {
    this.buffer = buffer.slice(offset, offset + length);
  }
}
 
Example 6
Source File: CountingReadStream.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Buffer event) {
    count += event.length();
    if (delegateDataHandler != null) {
        delegateDataHandler.handle(event);
    }
}
 
Example 7
Source File: DockerModuleHandle.java    From okapi with Apache License 2.0 5 votes vote down vote up
private void logHandler(Buffer b) {
  if (logSkip == 0 && b.getByte(0) < 3) {
    logSkip = 8;
  }
  if (b.length() > logSkip) {
    logBuffer.append(b.getString(logSkip, b.length()));
    logSkip = 0;
  } else {
    logSkip = logSkip - b.length();
  }
  if (logBuffer.length() > 0 && logBuffer.charAt(logBuffer.length() - 1) == '\n') {
    logger.info("{} {}", () -> id, () -> logBuffer.substring(0, logBuffer.length() - 1));
    logBuffer.setLength(0);
  }
}
 
Example 8
Source File: VxApiRequestBodyHandler.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
@Override
public void handle(Buffer buffer) {
	// 如果buffer为null或者不是支持解析的类型则返回
	if (buffer == null || !contentType.isDecodedSupport()) {
		return;
	}
	bodyLength += buffer.length();
	if (maxContentLength > 0 && bodyLength > maxContentLength) {
		return;
	}
	bodyBuffer.appendBuffer(buffer);
}
 
Example 9
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 10
Source File: PipedEndableWriteStream.java    From sfs with Apache License 2.0 5 votes vote down vote up
protected Buffer poll() {
    Buffer chunk = chunks.poll();
    if (chunk != null) {
        writesOutstanding -= chunk.length();
    }
    handleDrained();
    handleEnd();
    return chunk;
}
 
Example 11
Source File: Jukebox.java    From vertx-in-action with MIT License 5 votes vote down vote up
private void processReadBuffer(Buffer buffer) {
  logger.info("Read {} bytes from pos {}", buffer.length(), positionInFile);
  positionInFile += buffer.length();
  if (buffer.length() == 0) {
    closeCurrentFile();
    return;
  }
  for (HttpServerResponse streamer : streamers) {
    if (!streamer.writeQueueFull()) {
      streamer.write(buffer.copy());
    }
  }
}
 
Example 12
Source File: LimitedWriteEndableWriteStream.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public LimitedWriteEndableWriteStream write(Buffer data) {
    bytesWritten += data.length();
    if (bytesWritten > length) {
        JsonObject jsonObject = new JsonObject()
                .put("message", String.format("Content-Length must be between 0 and %d", length));

        throw new HttpRequestValidationException(HttpURLConnection.HTTP_BAD_REQUEST, jsonObject);
    }
    delegate.write(data);
    return this;
}
 
Example 13
Source File: Buffers.java    From sfs with Apache License 2.0 5 votes vote down vote up
public static Iterable<Buffer> partition(final Buffer input, final int size) {
    int length = input.length();
    if (length <= size) {
        return Collections.singletonList(input);
    } else {
        return () -> new SliceIterator(input, size);
    }
}
 
Example 14
Source File: SpyableKafkaProducerService.java    From vertx-kafka-service with Apache License 2.0 4 votes vote down vote up
private boolean isValid(Buffer buffer) {
    return buffer != null && buffer.length() > 0;
}
 
Example 15
Source File: FileUploadsUtil.java    From raml-module-builder with Apache License 2.0 4 votes vote down vote up
public static MimeMultipart MultiPartFormData(Buffer buffer, int sizeLimit, String encoding) throws IOException {

    int contentLength = buffer.length();
    ArrayList<Byte> vBytes = new ArrayList<>();
    byte[] b = new byte[1];
    int paramCount = 0;

    // if the file they are trying to upload is too big, throw an exception
    if(contentLength > sizeLimit) {
      throw new IOException("File has exceeded size limit.");
    }

    byte[] bytes = buffer.getBytes();

    byte[] separator = "\n".getBytes(Charset.forName(encoding));

    int endBoundaryPos = Bytes.indexOf(bytes, separator);

    //only copy the boundary (the first line) - not copying all content
    byte[] boundary = Arrays.copyOfRange(bytes, 0, endBoundaryPos + separator.length);

    return split(boundary, bytes, sizeLimit);

  }
 
Example 16
Source File: DefaultKafkaProducerService.java    From vertx-kafka-service with Apache License 2.0 4 votes vote down vote up
private boolean isValid(Buffer buffer) {
    return buffer != null && buffer.length() > 0;
}
 
Example 17
Source File: FrameParser.java    From vertx-stomp with Apache License 2.0 4 votes vote down vote up
private boolean isEmpty(Buffer buffer) {
  return buffer.toString().length() == 0 || buffer.toString().equals(CARRIAGE_RETURN)
      || buffer.length() == 1 && buffer.getByte(0) == 0;
}
 
Example 18
Source File: Bytes.java    From cava with Apache License 2.0 3 votes vote down vote up
/**
 * Wrap a full Vert.x {@link Buffer} as a {@link Bytes} value.
 *
 * <p>
 * Note that any change to the content of the buffer may be reflected in the returned value.
 *
 * @param buffer The buffer to wrap.
 * @return A {@link Bytes} value.
 */
static Bytes wrapBuffer(Buffer buffer) {
  checkNotNull(buffer);
  if (buffer.length() == 0) {
    return EMPTY;
  }
  return new BufferWrappingBytes(buffer);
}
 
Example 19
Source File: MutableBytes.java    From incubator-tuweni with Apache License 2.0 3 votes vote down vote up
/**
 * Wrap a full Vert.x {@link Buffer} as a {@link MutableBytes} value.
 *
 * <p>
 * Note that any change to the content of the buffer may be reflected in the returned value.
 *
 * @param buffer The buffer to wrap.
 * @return A {@link MutableBytes} value.
 */
static MutableBytes wrapBuffer(Buffer buffer) {
  checkNotNull(buffer);
  if (buffer.length() == 0) {
    return EMPTY;
  }
  return new MutableBufferWrappingBytes(buffer);
}
 
Example 20
Source File: Bytes.java    From incubator-tuweni with Apache License 2.0 3 votes vote down vote up
/**
 * Wrap a full Vert.x {@link Buffer} as a {@link Bytes} value.
 *
 * <p>
 * Note that any change to the content of the buffer may be reflected in the returned value.
 *
 * @param buffer The buffer to wrap.
 * @return A {@link Bytes} value.
 */
static Bytes wrapBuffer(Buffer buffer) {
  checkNotNull(buffer);
  if (buffer.length() == 0) {
    return EMPTY;
  }
  return new BufferWrappingBytes(buffer);
}