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

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

Introduction

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

Prototype

@GenIgnore(GenIgnore.PERMITTED_TYPE)
@Fluent
Buffer appendBytes(byte[] bytes);

Source Link

Document

Appends the specified byte[] to the end of the Buffer.

Usage

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

License:Apache License

@Override
public void encodeToWire(final Buffer buffer, final MSG msg) {
    buffer.appendBytes(msg.toByteArray());
}

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
 *//*ww w .j a  va  2 s . com*/
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:io.advantageous.qbit.vertx.BufferUtils.java

License:Apache License

public static void writeString(final Buffer buffer, final String value) {

    byte[] string = value.getBytes(StandardCharsets.UTF_8);
    buffer.appendShort((short) string.length);
    buffer.appendBytes(string);

}

From source file:io.github.jdocker.common.vertx.JacksonCodec.java

License:Apache License

@Override
public void encodeToWire(Buffer buffer, Object o) {
    ObjectWriter writer = mapper.writer();
    StringWriter w = new StringWriter();
    try {//from  w  ww.ja  v a 2  s . co m
        writer.withRootName(o.getClass().getSimpleName()).writeValue(w, o);
        buffer.appendBytes(w.toString().getBytes());
    } catch (IOException e) {
        throw new IllegalStateException("Cannot serialize into json: " + o, e);
    }

}

From source file:io.github.jdocker.common.vertx.JavaSerializingCodec.java

License:Apache License

@Override
public void encodeToWire(Buffer buffer, Object o) {
    try {/*from   w  ww.  ja v a 2s . c  om*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oss = new ObjectOutputStream(bos);
        oss.writeObject(o);
        oss.flush();
        buffer.appendBytes(bos.toByteArray());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.helixservice.feature.restclient.RestRequest.java

License:Open Source License

/**
 * Execute the request, with the expected response body marshaled
 * to a specific object type.//from  w  w  w . j  av a 2s  . c o  m
 *
 * @param responseType Type we expect the response to be marshaled to
 * @return RestResponse fluent interface
 * @throws SuspendExecution For Vert.x Sync
 */
public <T> RestResponse<T> asObject(Class<T> responseType) throws SuspendExecution {
    try {
        // Apply Params & Url Vars
        String modifiedUrlPath = addParameters(replaceUrlVars(urlPath));

        // Do request
        HttpClientRequest request;
        if (useDefaultHostAndPort) {
            request = httpClient.get().request(io.vertx.core.http.HttpMethod.valueOf(method.name()),
                    modifiedUrlPath);
        } else {
            request = httpClient.get().requestAbs(io.vertx.core.http.HttpMethod.valueOf(method.name()),
                    modifiedUrlPath);
        }

        // Set timeout, if requested
        if (timeoutInMs != null) {
            request.setTimeout(timeoutInMs);
        }

        // With headers
        request.headers().addAll(VertxTypeConverter.toVertxMultiMap(headers));

        // Write body if we need to
        Buffer body = Buffer.buffer();
        if (requestBody.isPresent()) {
            request.setChunked(true);
            Message message = marshallerSupplier.get().marshal(requestBody);

            List<String> contentTypes = message.getContentTypes();
            if (contentTypes != null && contentTypes.size() > 0) {
                request.putHeader("Content-Type", contentTypes);
            }

            body = body.appendBytes(message.getBody());
        }

        // Wait for response with Vert.x Sync
        HttpClientResponse httpClientResponse = getHttpClientResponse(request, body);
        Buffer bodyBuffer = getBuffer(httpClientResponse);

        return new RestResponse<>(httpClientResponse, bodyBuffer, marshallerSupplier, responseType);
    } catch (URISyntaxException | UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Unable to parse urlPath=" + urlPath, e);
    }
}

From source file:microservicerx.dht.routing.SerializableCodec.java

@Override
public void encodeToWire(Buffer buffer, KLASS s) {
    byte[] data = Serializer.serialize(s);
    int length = data.length;

    // Write data into given buffer
    buffer.appendInt(length);/*from  w  ww .  jav  a 2  s  .  co  m*/
    buffer.appendBytes(data);
}

From source file:org.eclipse.hono.service.http.HttpUtils.java

License:Open Source License

/**
 * Writes a JSON object to an HTTP response body.
 * <p>/*  w w  w  . ja v a2 s  .com*/
 * This method also sets the <em>content-type</em> and <em>content-length</em>
 * headers of the HTTP response accordingly but does not end the response.
 * 
 * @param response The HTTP response.
 * @param body The JSON object to serialize to the response body (may be {@code null}).
 * @throws NullPointerException if response is {@code null}.
 */
public static void setResponseBody(final HttpServerResponse response, final JsonObject body) {
    Objects.requireNonNull(response);
    if (body != null) {
        final Buffer buffer = Buffer.buffer();
        buffer.appendBytes(body.encodePrettily().getBytes(StandardCharsets.UTF_8));
        response.putHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON_UFT8)
                .putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(buffer.length())).write(buffer);
    }
}

From source file:org.entcore.common.storage.impl.GridfsStorage.java

License:Open Source License

private void writeBuffer(String id, Buffer buff, Long maxSize, String contentType, String filename,
        final JsonObject m, Handler<JsonObject> handler) {
    JsonObject save = new JsonObject();
    save.put("action", "save");
    save.put("content-type", contentType);
    save.put("filename", filename);
    if (id != null && !id.trim().isEmpty()) {
        save.put("_id", id);
    }//from   w w  w . jav  a2s.c  o  m
    final JsonObject metadata = (m != null) ? m
            : new JsonObject().put("content-type", contentType).put("filename", filename);
    if (metadata.getLong("size", 0l).equals(0l)) {
        metadata.put("size", buff.length());
    }
    if (maxSize != null && maxSize < metadata.getLong("size", 0l)) {
        handler.handle(new JsonObject().put("status", "error").put("message", "file.too.large"));
        return;
    }
    byte[] header = null;
    try {
        header = save.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        JsonObject json = new JsonObject().put("status", "error").put("message", e.getMessage());
        handler.handle(json);
    }
    if (header != null) {
        buff.appendBytes(header).appendInt(header.length);
        eb.send(gridfsAddress, buff, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> message) {
                handler.handle(message.body().put("metadata", metadata));
            }
        }));
    }
}

From source file:org.entcore.common.storage.impl.GridfsStorage.java

License:Open Source License

public void saveChunk(String id, Buffer buff, int n, String contentType, String filename, long fileSize,
        final Handler<JsonObject> handler) {
    JsonObject save = new JsonObject();
    save.put("action", "saveChunk");
    save.put("content-type", contentType);
    save.put("filename", filename);
    save.put("_id", id);
    save.put("n", n);
    save.put("length", fileSize);

    byte[] header = null;
    try {//from ww  w .ja  v  a 2 s.c  o  m
        header = save.toString().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        JsonObject json = new JsonObject().put("status", "error").put("message", e.getMessage());
        handler.handle(json);
    }
    if (header != null) {
        buff.appendBytes(header).appendInt(header.length);
        eb.send(gridfsAddress, buff, handlerToAsyncHandler(new Handler<Message<JsonObject>>() {
            @Override
            public void handle(Message<JsonObject> event) {
                handler.handle(event.body());
            }
        }));
    }
}