Java Code Examples for net.openhft.chronicle.bytes.Bytes#writeInt()

The following examples show how to use net.openhft.chronicle.bytes.Bytes#writeInt() . 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: RollEOFTest.java    From Chronicle-Queue with Apache License 2.0 6 votes vote down vote up
private void removeEOF(Path path) throws IOException {
    long blockSize = 64 << 10;
    long chunkSize = OS.pageAlign(blockSize);
    long overlapSize = OS.pageAlign(blockSize / 4);
    final MappedBytes mappedBytes = MappedBytes.mappedBytes(path.toFile(), chunkSize, overlapSize, false);
    mappedBytes.reserve(test);
    try {
        final Wire wire = WireType.BINARY_LIGHT.apply(mappedBytes);
        final Bytes<?> bytes = wire.bytes();
        bytes.readLimitToCapacity();
        bytes.readSkip(4);
        // move past header
        try (final SingleChronicleQueueStore qs = loadStore(wire)) {
            assertNotNull(qs);
            long l = qs.writePosition();
            long len = Wires.lengthOf(bytes.readVolatileInt(l));
            long eofOffset = l + len + 4L;
            bytes.writePosition(eofOffset);
            bytes.writeInt(0);
        }
    } finally {
        mappedBytes.release(test);
    }
}
 
Example 2
Source File: TcpChannelHub.java    From Chronicle-Network with Apache License 2.0 5 votes vote down vote up
/**
 * process system messages which originate from the server
 *
 * @param header      a value representing the type of message
 * @param messageSize the size of the message
 * @throws IOException if a buffer cannot be read
 */
private void processServerSystemMessage(final int header, final int messageSize) throws IOException {

    serverHeartBeatHandler.clear();
    final Bytes bytes = serverHeartBeatHandler;

    bytes.clear();
    @NotNull final ByteBuffer byteBuffer = (ByteBuffer) bytes.underlyingObject();
    byteBuffer.clear();
    // we have to first write the header back to the bytes so that is can be
    // viewed as a document
    bytes.writeInt(0, header);
    byteBuffer.position(SIZE_OF_SIZE);
    byteBuffer.limit(SIZE_OF_SIZE + messageSize);
    readBuffer(byteBuffer);

    bytes.readLimit(byteBuffer.position());

    final StringBuilder eventName = Wires.acquireStringBuilder();
    final Wire inWire = TcpChannelHub.this.wireType.apply(bytes);
    if (YamlLogging.showHeartBeats())
        logToStandardOutMessageReceived(inWire);
    inWire.readDocument(null, d -> {
                @NotNull final ValueIn valueIn = d.readEventName(eventName);
                if (EventId.heartbeat.contentEquals(eventName))
                    reflectServerHeartbeatMessage(valueIn);
                else if (EventId.onClosingReply.contentEquals(eventName))
                    receivedClosedAcknowledgement.countDown();

            }
    );
}
 
Example 3
Source File: NonClusteredSslIntegrationTest.java    From Chronicle-Network with Apache License 2.0 5 votes vote down vote up
@Override
public void process(@NotNull final Bytes in, @NotNull final Bytes out, final StubNetworkContext nc) {
    latch.countDown();
    try {
        if (nc.isAcceptor() && in.readRemaining() != 0) {
            final int magic = in.readInt();
            if (magic != 0xFEDCBA98)
                throw new IllegalStateException("Invalid magic number " + Integer.toHexString(magic));
            final long received = in.readLong();
            final int len = in.readInt();
            final byte[] tmp = new byte[len];
            in.read(tmp);
            if (DEBUG) {
                if (len > 10) {
                    System.out.printf("%s received payload of length %d%n", label, len);
                    System.out.println(in);
                } else {
                    System.out.printf("%s received [%d] %d/%s%n", label, tmp.length, received, new String(tmp, StandardCharsets.US_ASCII));
                }
            }
            operationCount++;
        } else if (!nc.isAcceptor()) {
            if (System.currentTimeMillis() > lastSent + 100L) {
                out.writeInt(0xFEDCBA98);
                out.writeLong((counter++));
                final String payload = "ping-" + (counter - 1);
                out.writeInt(payload.length());
                out.write(payload.getBytes(StandardCharsets.US_ASCII));
                if (DEBUG) {
                    System.out.printf("%s sent [%d] %d/%s%n", label, payload.length(), counter - 1, payload);
                }
                operationCount++;
                lastSent = System.currentTimeMillis();
            }
        }
    } catch (RuntimeException e) {
        System.err.printf("Exception in %s: %s/%s%n", label, e.getClass().getSimpleName(), e.getMessage());
        e.printStackTrace();
    }
}
 
Example 4
Source File: ListMarshaller.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Bytes out, @NotNull List<T> toWrite) {
    out.writeInt(toWrite.size());
    // indexed loop to avoid garbage creation
    //noinspection ForLoopReplaceableByForEach
    for (int i = 0; i < toWrite.size(); i++) {
        elementWriter.write(out, toWrite.get(i));
    }
}
 
Example 5
Source File: MapMarshaller.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Bytes out, @NotNull Map<K, V> toWrite) {
    out.writeInt(toWrite.size());
    toWrite.forEach((k, v) -> {
        keyWriter.write(out, k);
        valueWriter.write(out, v);
    });
}
 
Example 6
Source File: Issue43Test.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Bytes bytes, @NotNull ValueWrapper vw) {
    bytes.writeInt(vw.values.length);

    for (int i = 0; i < vw.values.length; i++) {
        bytes.writeDouble(vw.values[i]);
    }
}
 
Example 7
Source File: CharSequenceArrayBytesMarshaller.java    From Chronicle-Map with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Bytes out, @NotNull CharSequence[] toWrite) {
    // Note that the *array length*, not the *serialization size* is written in the beginning,
    // so BytesWriter + BytesReader is the most suitable pair of serialization interfaces
    // to implement for CharSequence[] type
    out.writeInt(toWrite.length);
    for (CharSequence cs : toWrite) {
        // Assume elements non-null for simplicity
        Objects.requireNonNull(cs);
        out.writeUtf8(cs);
    }
}
 
Example 8
Source File: RawAccessJava.java    From Chronicle-Queue with Apache License 2.0 5 votes vote down vote up
@Test
public void Appender() {
    if (!assert_from_cpp())
        return;

    String tmp = "/dev/shm/RawAccessJtoC";
    System.out.println(tmp); // so C++ knows this ran rather than skipped

    try (ChronicleQueue cq = SingleChronicleQueueBuilder.binary(tmp).build()) {

        ExcerptAppender appender = cq.acquireAppender();

        for (int i = 0; i < COUNT; ++i) {
            try (DocumentContext dc = appender.writingDocument()) {

                Bytes bytes = dc.wire().bytes();

                // will contain the size of the blob
                long start = bytes.writePosition();
                bytes.writeSkip(RAW_SIZE_PREFIX);

                {
                    bytes.writeByte((byte) 0xab);
                    bytes.writeShort((short) 12);
                    bytes.writeInt(123);
                    bytes.writeLong(123456789L);
                    bytes.writeFloat(1.234f);
                    bytes.writeDouble(123.456);
                    bytes.writeChar('a');
                    bytes.write8bit("Hello World");
                }

                long end = bytes.writePosition();
                bytes.writeInt(start, (int) (end - start - RAW_SIZE_PREFIX));
            }
        }
    }
}
 
Example 9
Source File: SetMarshaller.java    From Chronicle-Map with Apache License 2.0 4 votes vote down vote up
@Override
public void write(Bytes out, @NotNull Set<T> toWrite) {
    out.writeInt(toWrite.size());
    toWrite.forEach(e -> elementWriter.write(out, e));
}
 
Example 10
Source File: IntegerMarshaller.java    From Chronicle-Map with Apache License 2.0 4 votes vote down vote up
@Override
public void write(@NotNull Bytes out, long size, @NotNull Integer toWrite) {
    out.writeInt(toWrite);
}
 
Example 11
Source File: IntegerMarshaller.java    From Chronicle-Map with Apache License 2.0 4 votes vote down vote up
@Override
public void write(Bytes out, @NotNull Integer toWrite) {
    out.writeInt(toWrite);
}
 
Example 12
Source File: CharSequenceCustomEncodingBytesWriter.java    From Chronicle-Map with Apache License 2.0 4 votes vote down vote up
@Override
public void write(Bytes out, @NotNull CharSequence cs) {
    // Write the actual cs length for accurate StringBuilder.ensureCapacity() while reading
    out.writeStopBit(cs.length());
    long encodedSizePos = out.writePosition();
    out.writeSkip(4);
    charsetEncoder.reset();
    inputBuffer.clear();
    outputBuffer.clear();
    int csPos = 0;
    boolean endOfInput = false;
    // this loop inspired by the CharsetEncoder.encode(CharBuffer) implementation
    while (true) {
        if (!endOfInput) {
            int nextCsPos = Math.min(csPos + inputBuffer.remaining(), cs.length());
            append(inputBuffer, cs, csPos, nextCsPos);
            inputBuffer.flip();
            endOfInput = nextCsPos == cs.length();
            csPos = nextCsPos;
        }

        CoderResult cr = inputBuffer.hasRemaining() ?
                charsetEncoder.encode(inputBuffer, outputBuffer, endOfInput) :
                CoderResult.UNDERFLOW;

        if (cr.isUnderflow() && endOfInput)
            cr = charsetEncoder.flush(outputBuffer);

        if (cr.isUnderflow()) {
            if (endOfInput) {
                break;
            } else {
                inputBuffer.compact();
                continue;
            }
        }

        if (cr.isOverflow()) {
            outputBuffer.flip();
            writeOutputBuffer(out);
            outputBuffer.clear();
            continue;
        }

        try {
            cr.throwException();
        } catch (CharacterCodingException e) {
            throw new IORuntimeException(e);
        }
    }
    outputBuffer.flip();
    writeOutputBuffer(out);

    out.writeInt(encodedSizePos, (int) (out.writePosition() - encodedSizePos - 4));
}