### Java System Property Configuration Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/systemProperties.adoc
Demonstrates how to set Java system properties to influence Chronicle library behavior. This is typically done at JVM startup using the -D flag.
```bash
# Example: Enable dumping of generated bytecode
java -DdumpCode=true -jar your-application.jar
# Example: Disable padding in binary wire formats
java -Dwire.usePadding=false -jar your-application.jar
# Example: Force tests to write YAML
java -Dwire.testAsYaml=true -jar your-application.jar
```
--------------------------------
### Text Wire Format Example (YAML)
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Demonstrates the Text Wire format using YAML. This format is easy to implement, document, and debug, offering a human-readable representation of data. The example shows basic data types like integers, booleans, and strings.
```yaml
--- !!data
price: 1234
flag: true
text: Hello World!
side: Sell
smallInt: 123
longInt: 1234567890
```
--------------------------------
### Binary Wire Format Example (YAML)
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Presents the default Binary Wire format, which can be automatically decoded to text. This format is optimized for speed and uses a YAML-like structure with binary encoding. The example includes typical data fields.
```yaml
--- !!data #binary
price: 1234
flag: true
text: Hello World!
side: Sell
smallInt: 123
longInt: 1234567890
```
--------------------------------
### Simple TextWire Example in Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
A basic Java example demonstrating the creation of a TextWire, writing a 'message' to it, and printing the resulting byte buffer's content. It utilizes `Bytes.allocateElasticOnHeap()` for buffer management.
```java
Bytes> bytes = Bytes.allocateElasticOnHeap();
Wire wire = WireType.TEXT.apply(bytes);
wire.write("message").text("Hello World");
System.out.println(bytes.toString());
```
--------------------------------
### Java Runnable Code Examples for Chronicle Wire
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/project-requirements.adoc
A collection of self-contained Java source files demonstrating significant code examples for Chronicle Wire. These are intended to be included directly in documentation or linked from a separate examples directory. Accompanying build configuration snippets (like pom.xml) are expected to show necessary dependencies.
```java
public class Example {
// Main method for example execution
public static void main(String[] args) {
// Code demonstrating Chronicle Wire functionality
System.out.println("Chronicle Wire Example");
}
}
```
```xml
net.openhft
chronicle-wire
LATEST_VERSION
```
--------------------------------
### RawWire Format Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Presents the RawWire format, which drops all metadata and requires fixed-width data due to the absence of compact types. This format is highly efficient for specific, known data structures. The example shows a hexadecimal dump.
```text
00000000 27 00 00 00 00 00 00 00 00 48 93 40 B1 0C 48 65 '······· ·H·@··He
00000010 6C 6C 6F 20 57 6F 72 6C 64 21 04 53 65 6C 6C 7B llo Worl d!·Sell{
00000020 00 00 00 D2 02 96 49 00 00 00 00 ······I· ···
```
--------------------------------
### JSON Wire Format Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Illustrates the JSON Wire format, which produces a JSON-style output with YAML-based extensions for typed data. This format is compact and widely compatible. The example includes common data types.
```json
--- !!data
"price":1234,"longInt":1234567890,"smallInt":123,"flag":true,"text":"Hello World!","side":"Sell"
```
--------------------------------
### Boon Output Example (JSON)
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Demonstrates the JSON output produced by the Boon library. Boon is a high-performance JSON library for Java. This example shows a typical JSON object structure with various data types.
```json
{"smallInt":123,"longInt":1234567890,"price":1234.0,"flag":true,"side":"Sell","text":"Hello World!"}
```
--------------------------------
### Jackson Output Example (JSON)
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Shows the JSON output generated by the Jackson library, a widely-used Java data-processing tool for JSON. The example includes common data types and demonstrates Jackson's JSON serialization capabilities.
```json
{"price":1234.0,"flag":true,"text":"Hello World!","side":"Sell","smallInt ":123,"longInt":1234567890}
```
--------------------------------
### NanoTime Annotation Example in YAML
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/wire-annotations.adoc
This YAML example demonstrates the output of a `LogEntry` object using the @NanoTime annotation. The `eventTimestamp` field is represented as a human-readable ISO 8601 formatted string, showcasing the text format behavior of the @NanoTime annotation.
```yaml
!LogEntry {
eventTimestamp: 2025-05-30T07:30:05.123456789Z, // ISO 8601 format
message: System initialised
}
```
--------------------------------
### BytesMarshallable Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Demonstrates the BytesMarshallable format, which uses fixed-width data types for efficient serialization. This format is suitable for scenarios requiring predictable data sizes. The example is presented as a hexadecimal dump.
```text
00000000 23 00 00 00 00 00 00 00 00 48 93 40 D2 02 96 49 #······· ·H·@···I
00000010 00 00 00 00 7B 00 00 00 59 00 0C 48 65 6C 6C 6F ····{··· Y··Hello
00000020 20 57 6F 72 6C 64 21 World!
```
--------------------------------
### YAML Anchors and Aliases Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Demonstrates the usage of YAML anchors (`&`) and aliases (`*`) in Chronicle Wire for reusing values. This example shows how a database host is defined once and then referenced multiple times in different configurations (cache, backup) to ensure consistency and reduce redundancy.
```yaml
database:
host: &dbHost "production.example.com"
port: 5432
username: admin
cache:
host: *dbHost # Reuses the same host
port: 6379
timeout: 30
backup:
host: *dbHost # Reuses the same host
port: 5432 # The port is not anchored, so it's a separate value
schedule: "0 2 * * *"
```
--------------------------------
### Binary Wire with Field Numbers (YAML)
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Demonstrates the Binary Wire format using field numbers for more efficient writing and reading. While less human-friendly, this approach significantly reduces data size. The example uses numeric keys for fields.
```yaml
--- !!data #binary
3: 1234
4: true
5: Hello World!
6: Sell
1: 123
2: 1234567890
```
--------------------------------
### Java Example: Initializing Different Wire Types
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Demonstrates how to initialize different wire types (TextWire, BinaryWire, RawWire) using a provided Bytes buffer. It shows direct instantiation and using WireType enums.
```java
Wire wire = new TextWire(bytes);
// or
WireType wireType = WireType.TEXT;
Wire wireB = wireType.apply(bytes);
// or
Bytes> bytes2 = Bytes.allocateElasticOnHeap();
Wire wire2 = new BinaryWire(bytes2);
// or
Bytes> bytes3 = Bytes.allocateElasticOnHeap();
Wire wire3 = new RawWire(bytes3);
```
--------------------------------
### Asciidoc List Indentation Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/AGENTS.md
Demonstrates the correct way to indent list items in Asciidoc, emphasizing the use of asterisks for hierarchy over relying on whitespace.
```asciidoc
section :: Top Level Section (Optional)
* first level
** nested level
```
--------------------------------
### Binary Wire with Variable Width Values Only (YAML)
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Shows a Binary Wire format that exclusively uses variable-width values. This approach minimizes data size by not including field numbers or fixed-width constraints. The example lists values directly.
```yaml
--- !!data #binary
1234
true
Hello World!
Sell
123
1234567890
```
--------------------------------
### Java Object Anchors Example: Reusing ServerConfig Instances
Source: https://context7.com/openhft/chronicle-wire/llms.txt
Demonstrates how to reuse entire object instances across configurations using YAML anchors and aliases in Chronicle Wire. This example defines ServerConfig, MonitorConfig, and ServerSystemConfig, and shows how references to the same ServerConfig are resolved to a single instance.
```java
class ServerConfig extends SelfDescribingMarshallable {
int timeout;
int retries;
String logLevel;
}
class MonitorConfig extends SelfDescribingMarshallable {
ServerConfig server;
int interval;
}
String yaml = """
defaults: &defaultServer !ServerConfig {
timeout: 30,
retries: 3,
logLevel: INFO
}
primary: *defaultServer
secondary: *defaultServer
monitoring: {
server: *defaultServer,
interval: 60
}
""";
class ServerSystemConfig extends SelfDescribingMarshallable {
ServerConfig defaults;
ServerConfig primary;
ServerConfig secondary;
MonitorConfig monitoring;
}
ServerSystemConfig config = WireType.YAML.fromString(ServerSystemConfig.class, yaml);
// All references point to the same ServerConfig instance
assert config.defaults == config.primary;
assert config.defaults == config.secondary;
assert config.defaults == config.monitoring.server;
assert config.defaults.timeout == 30;
```
--------------------------------
### SnakeYAML Output Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Illustrates the output generated by SnakeYAML, a popular Java YAML parser and emitter. It shows how SnakeYAML might represent data, including using '.0' to signify floating-point numbers for types like 'price'.
```yaml
flag: true
longInt: 1234567890
price: 1234.0
side: Sell
smallInt: 123
text: Hello World!
```
--------------------------------
### YAML Representation of MyData
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Illustrates YAML examples for using 'MyData' objects. It shows how to reference predefined values ('One', 'Two') and how to define new instances with a 'name' field, which can then be used directly.
```yaml
myData: One # uses predefined value
...
myData: Two # uses predefined value
...
refData: {
eventId: GUI,
eventTime: 2020-09-09T09:09:09.999,
data: !MyData {
name: Three
}
}
...
myData: Three # use the one just defined
...
myData: Four # will error as doesn't exist.
...
```
--------------------------------
### Chronicle Channel EchoHandler Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Demonstrates setting up a TCP server, creating a channel that acts as an EchoHandler, sending messages, and receiving them back. It uses ChronicleContext for channel management and ChronicleChannel for communication, with methodWriter for sending and readOne for receiving.
```java
String url = "tcp://:0";
try (ChronicleContext context = ChronicleContext.newContext(url)) {
ChronicleChannel channel = context.newChannelSupplier(new EchoHandler()).get();
Says say = channel.methodWriter(Says.class);
say.say("Hello World");
say.say("Bye now");
StringBuilder event = new StringBuilder();
String text = channel.readOne(event, String.class);
assertEquals("say: Hello World", event + ": " + text);
String text2 = channel.readOne(event, String.class);
assertEquals("say: Bye now", event + ": " + text2);
}
```
--------------------------------
### SBE (Simple Binary Encoding) Hexadecimal Representation Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Provides a hexadecimal dump of data serialized using SBE (Simple Binary Encoding). SBE is a high-performance, language-neutral binary encoding standard. The example shows the binary structure of SBE encoded data.
```text
00000000 29 00 7B 00 00 00 D2 02 96 49 00 00 00 00 00 00 )·{····· ·I······
00000010 00 00 00 48 93 40 01 0C 48 65 6C 6C 6F 20 57 6F ···H·@·· Hello Wo
00000020 72 6C 64 21 00 00 00 00 01 00 00 rld!···· ···
```
--------------------------------
### Binary Marshalling with Versioning in Java
Source: https://context7.com/openhft/chronicle-wire/llms.txt
Illustrates manual schema evolution for a high-performance binary format using `BytesInBinaryMarshallable`. This example shows how to manage different versions of a data structure, adding new fields (like 'email' in version 2) while maintaining backward compatibility.
```java
import net.openhft.chronicle.wire.BytesInBinaryMarshallable;
import net.openhft.chronicle.bytes.BytesOut;
import net.openhft.chronicle.bytes.BytesIn;
class VersionedBinaryData extends BytesInBinaryMarshallable {
private static final int VERSION_1 = 1;
private static final int VERSION_2 = 2;
private static final int CURRENT_VERSION = VERSION_2;
String name;
int age;
String email; // added in version 2
@Override
public void writeMarshallable(BytesOut> out) {
out.writeStopBit(CURRENT_VERSION);
out.writeUtf8(name);
out.writeInt(age);
if (CURRENT_VERSION >= VERSION_2) {
out.writeUtf8(email != null ? email : "");
}
}
@Override
public void readMarshallable(BytesIn> in) {
int version = (int) in.readStopBit();
name = in.readUtf8();
age = in.readInt();
if (version >= VERSION_2) {
email = in.readUtf8();
if (email.isEmpty()) email = null;
}
}
}
// Write with current version
VersionedBinaryData data = new VersionedBinaryData();
data.name = "Alice";
data.age = 30;
data.email = "alice@example.com";
Bytes> bytes = Bytes.allocateElasticOnHeap();
data.writeMarshallable(bytes);
// Read handles both old and new versions
VersionedBinaryData read = new VersionedBinaryData();
read.readMarshallable(bytes);
bytes.releaseLast();
```
--------------------------------
### Java Example: Allocating Byte Buffers
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Illustrates two ways to allocate byte buffers in Java for use with Chronicle Wire: `Bytes.allocateElasticOnHeap()` for heap-based byte arrays and `Bytes.elasticByteBuffer()` for dynamically resizing ByteBuffers.
```java
// Bytes which wraps a byte[]
Bytes bytes = Bytes.allocateElasticOnHeap();
// or
// Bytes which wraps a ByteBuffer which is resized as needed.
Bytes bytes = Bytes.elasticByteBuffer();
```
--------------------------------
### Java Example: Marshalling Data Objects to TextWire
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Shows how to write a custom data object (assumed to implement `writeMarshallable`) to a TextWire. This is a more object-oriented approach to data serialization.
```java
// Bytes which wraps a ByteBuffer which is resized as needed.
Bytes bytes = Bytes.elasticByteBuffer();
Wire wire = new TextWire(bytes);
Data data = new Data("Hello World", 1234567890L, TimeUnit.NANOSECONDS, 10.50);
data.writeMarshallable(wire);
System.out.println(bytes);
```
--------------------------------
### Chained Event Example in Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Demonstrates how to chain event calls in Java using the Chronicle Wire library. This allows for fluent construction of event sequences.
```java
eg.via("target").at(now).say("Hello World");
```
--------------------------------
### BytesMarshallable with Stop Bit Encoding Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Shows BytesMarshallable utilizing stop bit encoding to reduce message size. This technique is effective for compressing numerical data, leading to smaller payloads. The example is provided as a hexadecimal dump.
```text
00000000 18 00 00 00 A0 A4 69 D2 85 D8 CC 04 7B 59 00 0C ······i· ····{Y··
00000010 48 65 6C 6C 6F 20 57 6F 72 6C 64 21 Hello Wo rld!
```
--------------------------------
### YAML Anchors and Aliases for Value Reuse in Java
Source: https://context7.com/openhft/chronicle-wire/llms.txt
Demonstrate reusing common configuration values across different sections in YAML using anchors (&) and aliases (*). This example defines a SystemConfig with multiple DatabaseConfig instances, where the database host is shared using an anchor.
```java
import net.openhft.chronicle.wire.WireType;
import net.openhft.chronicle.core.io.SelfDescribingMarshallable;
// Assuming DatabaseConfig and SystemConfig classes are defined as follows:
// class DatabaseConfig extends SelfDescribingMarshallable {
// String host;
// int port;
// String username;
// }
//
// class SystemConfig extends SelfDescribingMarshallable {
// DatabaseConfig database;
// DatabaseConfig cache;
// DatabaseConfig backup;
// }
String yaml = """
database: {\n host: &dbHost "production.example.com",\n port: 5432,\n username: admin\n}
cache: {\n host: *dbHost,\n port: 6379,\n username: cache_user\n}
backup: {\n host: *dbHost,\n port: 5433,\n username: backup\n}
""";
SystemConfig config = WireType.YAML.fromString(SystemConfig.class, yaml);
// All three configs share the same host string instance
assert config.database.host == config.cache.host;
assert config.database.host == config.backup.host;
assert config.database.host.equals("production.example.com");
```
--------------------------------
### Java Example: Writing Multiple Fields to BinaryWire
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Demonstrates writing the same set of data fields (String, long, Enum, double) to a BinaryWire and printing its hexadecimal representation. This is useful for performance-sensitive applications.
```java
// The same code for BinaryWire
wire2.write("message").text("Hello World")
.write("number").int64(1234567890L)
.write("code").asEnum(TimeUnit.SECONDS)
.write("price").float64(10.50);
System.out.println(bytes2.toHexString());
```
--------------------------------
### BSON Hexadecimal Representation Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
Presents a hexadecimal dump of data serialized in the BSON (Binary JSON) format. BSON is a binary-encoded serialization of JSON-like documents, commonly used in MongoDB. The dump shows the binary structure.
```text
00000000 60 00 00 00 01 70 72 69 63 65 00 00 00 00 00 00 `····pri ce······
00000010 48 93 40 08 66 6C 61 67 00 01 02 74 65 78 74 00 H·@·flag ···text·
00000020 0D 00 00 00 48 65 6C 6C 6F 20 57 6F 72 6C 64 21 ····Hell o World!
00000030 00 02 73 69 64 65 00 05 00 00 00 53 65 6C 6C 00 ··side·· ···Sell·
00000040 10 73 6D 61 6C 6C 49 6E 74 00 7B 00 00 00 12 6C ·smallIn t·{····l
00000050 6F 6E 67 49 6E 74 00 D2 02 96 49 00 00 00 00 00 ongInt·· ··I·····
```
--------------------------------
### Java Example: Writing Multiple Fields to TextWire
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Shows how to write various data types (String, long, Enum, double) to a TextWire and then print the resulting byte buffer. This demonstrates a structured way to record data.
```java
wire.write("message").text("Hello World")
.write("number").int64(1234567890L)
.write("code").asEnum(TimeUnit.SECONDS)
.write("price").float64(10.50);
System.out.println(bytes);
```
--------------------------------
### Chronicle Wire Basic Serialization (YAML, JSON, Binary)
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/project-requirements.adoc
Provides examples of basic serialization for simple Plain Old Java Objects (POJOs) using different WireTypes like YAML, JSON, and Binary, demonstrating the fundamental serialization capabilities of Chronicle Wire.
```java
import net.openhft.chronicle.core.util.IoUtils;
import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.Wire;
import net.openhft.chronicle.wire.WireType;
import java.io.IOException;
// Simple POJO to serialize
class SimplePojo {
private String name;
private int value;
public SimplePojo() {}
public SimplePojo(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() { return name; }
public int getValue() { return value; }
@Override
public String toString() {
return "SimplePojo{name='" + name + "', value=" + value + '}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SimplePojo that = (SimplePojo) o;
return value == that.value && name.equals(that.name);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + value;
return result;
}
}
public class BasicSerializationExample {
public static void main(String[] args) throws IOException {
SimplePojo originalPojo = new SimplePojo("TestObject", 123);
// --- YAML Serialization ---
System.out.println("--- YAML Serialization ---");
serializeDeserialize(originalPojo, WireType.YAML);
// --- JSON Serialization ---
System.out.println("\n--- JSON Serialization ---");
serializeDeserialize(originalPojo, WireType.JSON);
// --- Binary Serialization ---
System.out.println("\n--- Binary Serialization ---");
serializeDeserialize(originalPojo, WireType.BINARY);
}
private static void serializeDeserialize(SimplePojo pojo, WireType wireType) throws IOException {
// Create a Wire instance (using a String as backing store for simplicity)
// In real applications, you'd use Bytes or File channels.
Wire wire = wireType.apply("temp-buffer");
try {
// Write the POJO
wire.writeDocument(w -> w.object(pojo));
String serializedData = wire.toString();
System.out.println("Serialized: " + serializedData);
// Reset the wire for reading
wire.clear();
// Re-parse the string data into the wire.
// NOTE: For actual Bytes/File based wires, you'd read directly.
// This part is a simplification for demonstration.
if (wireType == WireType.BINARY) {
// Binary wire needs to be recreated from bytes for reading demonstration
// For simplicity, we won't show binary re-parsing from string here.
// In practice, you'd read from the Bytes buffer directly.
System.out.println("Binary serialization output is raw bytes, not easily represented as string here.");
} else {
// For YAML and JSON, we can represent it as a string and parse
wire.methodReader(new ObjectReader() {
@Override
public void readObject(String key, Object o) {
if (o instanceof SimplePojo) {
SimplePojo deserializedPojo = (SimplePojo) o;
System.out.println("Deserialized: " + deserializedPojo);
if (pojo.equals(deserializedPojo)) {
System.out.println("Serialization/Deserialization successful!");
} else {
System.err.println("Deserialized object does not match original!");
}
} else {
System.err.println("Unexpected object type during deserialization: " + o.getClass().getName());
}
}
}).readOne(); // This is a simplified way to trigger reading from the wire.
// A more direct approach would be:
// wire.readDocument(dc -> {
// SimplePojo deserialized = dc.wire().read().object(SimplePojo.class);
// System.out.println("Deserialized: " + deserialized);
// });
}
} finally {
// Clean up the wire's resources if any
wire.close();
IoUtils.delete(wire.toString(), true); // Attempt to clean up if it wrote to a file
}
}
// Helper interface for demonstrating reading
interface ObjectReader {
void readObject(String key, Object o);
}
}
```
--------------------------------
### Java Example: Writing Multiple Fields to RawWire
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Illustrates writing data to a RawWire, which omits metadata for reduced size and increased speed. The output is shown in hexadecimal format, highlighting the stripped-down data.
```java
// The same code for RawWire
wire3.write("message").text("Hello World")
.write("number").int64(1234567890L)
.write("code").asEnum(TimeUnit.SECONDS)
.write("price").float64(10.50);
System.out.println(bytes3.toHexString());
```
--------------------------------
### Java: Count Excerpts with Reduction
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/java/net/openhft/chronicle/wire/domestic/reduction/README.adoc
This example shows how to create a Reduction that simply counts the number of excerpts encountered in a Chronicle Queue. It utilizes the Reductions.counting() method to initialize the reduction and then demonstrates how to access the current count.
```java
Reduction counting = Reductions.counting() <1>
...
long count = counting.reduction().getAsLong(); <2>
```
--------------------------------
### Text: Example Reduction Accumulation Output
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/java/net/openhft/chronicle/wire/domestic/reduction/README.adoc
This shows a sample output of a Chronicle Reduction's accumulation, specifically for MarketData objects keyed by symbol. It displays the structure of the aggregated data, including symbols and their corresponding MarketData details.
```text
accumulation.accumulation() = {MSFT=!MarketData {
symbol: MSFT,
last: 101.0,
high: 110.0,
low: 90.0
}
, APPL=!MarketData {
symbol: AAPL,
last: 200.0,
high: 220.0,
low: 180.0
}
}
```
--------------------------------
### Boolean System Property Parsing in Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/systemProperties.adoc
Illustrates the Java code snippet used by Chronicle to parse boolean system properties. It checks for the property's presence or explicit 'true'/'yes' values.
```java
boolean isDumpCodeEnabled = net.openhft.chronicle.core.Jvm.getBoolean("dumpCode", false);
boolean isMappedFileRetained = net.openhft.chronicle.core.Jvm.getBoolean("mappedFile.retain", false);
boolean isRegressTestsActive = net.openhft.chronicle.core.Jvm.getBoolean("regress.tests", false);
boolean shouldGenerateTuples = net.openhft.chronicle.core.Jvm.getBoolean("wire.generate.tuples", false);
boolean shouldPrependPackage = net.openhft.chronicle.core.Jvm.getBoolean("wire.method.prependPackage", false);
boolean isTestAsYaml = net.openhft.chronicle.core.Jvm.getBoolean("wire.testAsYaml", false);
boolean usePadding = net.openhft.chronicle.core.Jvm.getBoolean("wire.usePadding", true);
boolean isYamlLoggingEnabled = net.openhft.chronicle.core.Jvm.getBoolean("yaml.logging", false);
```
--------------------------------
### Say one text message - Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Demonstrates sending a text message event using the 'say' method. This is a basic example of event messaging with a String argument.
```java
eg.say("Hello World");
```
--------------------------------
### YAML for New ServerId Definition
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Provides a YAML example for adding a new enum value ('HK_A') to 'ServerId' that may not have existed previously. This demonstrates the flexibility of Chronicle Wire in handling new enum definitions dynamically.
```yaml
refData: {
eventId: GUI,
eventTime: 2020-09-09T09:09:09.999,
data: !ServerId {
name: HK_A,
priority: 200
}
}
```
--------------------------------
### Add Chronicle Wire Maven Dependency
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
This snippet shows how to include the Chronicle Wire library in your Maven project. Ensure you have Maven configured correctly to fetch dependencies from Maven Central. This is the primary step to start using Chronicle Wire in your Java applications.
```xml
net.openhft
chronicle-wire
0.25.0
```
--------------------------------
### Verify Build and Tests with Maven
Source: https://github.com/openhft/chronicle-wire/blob/ea/AGENTS.md
This command cleans the project, compiles the code, and runs all unit tests. It's essential to ensure the project builds successfully and all tests pass before submitting changes. The command should exit with code 0 upon success.
```bash
# From repo root
mvn -q clean verify
```
--------------------------------
### Java: Implement Marshalling and Unmarshalling for Wire Formats
Source: https://github.com/openhft/chronicle-wire/blob/ea/microbenchmarks/README.md
This code demonstrates how to implement the `readMarshallable` and `writeMarshallable` methods for serializing and deserializing data using Chronicle Wire. It shows how to read and write various data types including floats, booleans, strings, enums, and integers. This implementation is typically placed within the class that needs to be serialized.
```java
@Override
public void readMarshallable(WireIn wire) throws IllegalStateException {
wire.read(DataFields.price).float64(setPrice)
.read(DataFields.flag).bool(setFlag)
.read(DataFields.text).text(text)
.read(DataFields.side).asEnum(Side.class, setSide)
.read(DataFields.smallInt).int32(setSmallInt)
.read(DataFields.longInt).int64(setLongInt);
}
@Override
public void writeMarshallable(WireOut wire) {
wire.write(DataFields.price).float64(price)
.write(DataFields.flag).bool(flag)
.write(DataFields.text).text(text)
.write(DataFields.side).asEnum(side)
.write(DataFields.smallInt).int32(smallInt)
.write(DataFields.longInt).int64(longInt);
}
```
--------------------------------
### Java: Collect All MarketData Elements into a List with Reduction
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/java/net/openhft/chronicle/wire/domestic/reduction/README.adoc
This example demonstrates creating a Reduction that accumulates all MarketData elements encountered in a Chronicle Queue into a List. It's important to note that this approach can consume significant heap memory if the queue contains a large number of elements.
```java
Reduction> listing =
```
--------------------------------
### Demonstrate Schema Evolution with Chronicle Wire (Java)
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/wire-cookbook.adoc
A Java demo illustrating schema evolution by writing data with a newer version (`VersionedDataV2`) and reading it with an older version's perspective, and vice-versa. It uses Chronicle Wire's YAML serialization to show how new fields are handled (default values) when reading older data.
```Java
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.wire.Wire;
import net.openhft.chronicle.wire.WireType;
import net.openhft.chronicle.wire.Wires;
import net.openhft.chronicle.core.ClassAliasPool;
// Assuming VersionedDataV1 and VersionedDataV2 are in com.example.evo package
// and class aliasing is set up if needed, or you deserialize to explicit class.
public class SchemaEvolutionDemo {
public static void main(String[] args) {
// Scenario 1: New code writes V2, old code (conceptually) reads V1
// (We'll simulate old code reading by attempting to read V2 data as V1 structure if possible,
// or more practically, new code reading old V1 data)
// Data written by V2 component
com.example.evo.VersionedDataV2 dataV2 = new com.example.evo.VersionedDataV2("test", 100);
Bytes> bytesV2 = Bytes.elasticByteBuffer();
Wire wireWriteV2 = WireType.YAML_ONLY.apply(bytesV2);
ClassAliasPool.CLASS_ALIASES.addAlias(com.example.evo.VersionedDataV2.class, "VersionedData");
ClassAliasPool.CLASS_ALIASES.addAlias(com.example.evo.VersionedDataV1.class, "VersionedData");
wireWriteV2.write("yaml").object(dataV2);
String v2DataAsString = bytesV2.toString();
System.out.println("Data written by V2:\n" + v2DataAsString);
// Scenario 2: New code (expecting V2) reads data written by V1 component
com.example.evo.VersionedDataV1 dataV1 = new com.example.evo.VersionedDataV1("old data");
Bytes> bytesV1 = Bytes.elasticByteBuffer();
Wire wireWriteV1 = WireType.YAML_ONLY.apply(bytesV1);
// If VersionedDataV1 was aliased to "VersionedData"
wireWriteV1.write("yaml").object(dataV1);
String v1DataAsString = bytesV1.toString();
System.out.println("\nData written by V1:\n" + v1DataAsString);
// New code reads V1 data
Bytes> bytesV1toRead = Bytes.fromString(v1DataAsString);
Wire wireReadV1AsV2 = WireType.YAML_ONLY.apply(bytesV1toRead);
com.example.evo.VersionedDataV2 readAsV2 = wireReadV1AsV2.getValueIn().object(com.example.evo.VersionedDataV2.class);
System.out.println("\nNew code (V2) reading V1 data:");
System.out.println(" ExistingField: " + readAsV2.existingField());
System.out.println(" NewField: " + readAsV2.newField() + " (gets default int value 0)");
bytesV1.releaseLast();
bytesV2.releaseLast();
}
}
```
--------------------------------
### POJO with List using SelfDescribingMarshallable (Java)
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
This Java code demonstrates creating a POJO (`MyPojo`) and a container POJO (`MyPojos`) that includes a list of `MyPojo` objects. By extending `SelfDescribingMarshallable`, these classes automatically get implementations for serialization, deserialization, `toString()`, `hashCode()`, and `equals()` methods, reducing boilerplate code.
```java
import net.openhft.chronicle.wire.SelfDescribingMarshallable;
class MyPojo extends SelfDescribingMarshallable {
String text;
int num;
double factor;
public MyPojo(String text, int num, double factor) {
this.text = text;
this.num = num;
this.factor = factor;
}
}
class MyPojos extends SelfDescribingMarshallable {
String name;
List myPojos = new ArrayList<>();
public MyPojos(String name) {
this.name = name;
}
}
```
--------------------------------
### Decision Record Template for Documentation
Source: https://github.com/openhft/chronicle-wire/blob/ea/AGENTS.md
A template for documenting decisions, including context, statement, alternatives considered, rationale, impact, and notes. This helps maintain a structured record of project choices.
```asciidoc
=== [Identifier] Title of Decision
Date :: YYYY-MM-DD
Context ::
* What is the issue that this decision addresses?
* What are the driving forces, constraints, and requirements?
Decision Statement :: What is the change that is being proposed or was decided?
Alternatives Considered ::
* [Alternative 1 Name/Type]:
** *Description:* Brief description of the alternative.
** *Pros:* ...
** *Cons:* ...
* [Alternative 2 Name/Type]:
** *Description:* Brief description of the alternative.
** *Pros:* ...
** *Cons:* ...
Rationale for Decision ::
* Why was the chosen decision selected?
* How does it address the context and outweigh the cons of alternatives?
Impact & Consequences ::
* What are the positive and negative consequences of this decision?
* How does this decision affect the system, developers, users, or operations?
- What are the trade-offs made?
Notes/Links ::
** (Optional: Links to relevant issues, discussions, documentation, proof-of-concepts)
```
--------------------------------
### FIELDLESS_BINARY Data Structure Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/wire-schema-evolution.adoc
Demonstrates the structure of data serialized using the FIELDLESS_BINARY wire format. In this format, data is written as a direct sequence of field values in the exact order declared in the Marshallable class, omitting field names and numbers for performance and compactness. Changes in field order, type, or count will break deserialization.
```java
class MyFieldlessData extends SelfDescribingMarshallable {
int fieldA;
long fieldB;
// Wire output is just: (binary int for fieldA)(binary long for fieldB)
}
```
--------------------------------
### Filter and Collect Symbols Starting with 'S' into a Set
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/java/net/openhft/chronicle/wire/domestic/reduction/README.adoc
Extracts MarketData objects, maps them to their symbols, filters symbols starting with 'S', and collects them into a concurrent Set.
```java
Reduction> symbolsStartingWithS = Reduction.of(
builder(MarketData.class).build() <1>
.map(MarketData::symbol) <2>
.filter(s -> s.startsWith("S")))
.collecting(ConcurrentCollectors.toConcurrentSet());
```
--------------------------------
### Serialize POJO to YAML, JSON, and Binary Light using Chronicle Wire
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/wire-cookbook.adoc
Demonstrates serializing a `MyData` POJO into YAML, JSON, and Binary Light formats using Chronicle Wire. It utilizes `Bytes.elasticByteBuffer()` for dynamic byte buffer management and different `WireType` instances for format specification.
```java
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.wire.Wire;
import net.openhft.chronicle.wire.WireType;
public class BasicSerialisationDemo {
public static void main(String[] args) {
MyData data = new MyData("Hello Wire!", 123, 45.67);
// Serialize to YAML
Bytes> yamlBytes = Bytes.elasticByteBuffer();
Wire yamlWire = WireType.YAML_ONLY.apply(yamlBytes); // YAML_ONLY for pure YAML output
yamlWire.getValueOut().object(data);
System.out.println("YAML Output:\n" + yamlBytes);
yamlBytes.releaseLast();
// Serialize to JSON
Bytes> jsonBytes = Bytes.elasticByteBuffer();
Wire jsonWire = WireType.JSON_ONLY.apply(jsonBytes); // JSON_ONLY for pure JSON output
jsonWire.getValueOut().object(data);
System.out.println("\nJSON Output:\n" + jsonBytes);
jsonBytes.releaseLast();
// Serialize to Binary Light (common for performance)
Bytes> binaryBytes = Bytes.elasticByteBuffer();
Wire binaryWire = WireType.BINARY_LIGHT.apply(binaryBytes);
binaryWire.getValueOut().object(data);
System.out.println("\nBinary Light Output (hex):\n" + binaryBytes.toHexString());
// For demonstration, let's see how it would look if read back as YAML
// (This requires the binary data to be self-describing enough, BINARY_LIGHT is)
Wire binaryAsYaml = WireType.YAML_ONLY.apply(binaryBytes.readPosition(0)); // Reset read position
```
--------------------------------
### Timestamp as Long - Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Example of sending a timestamp as a long value, using NanoTimestampLongConverter for parsing.
```java
eg.timeNanos(NanoTimestampLongConverter.INSTANCE.parse("2022-04-29T08:24:17.44500531"));
```
--------------------------------
### No Arguments - Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Example of calling an event method with no arguments. This is used for simple event triggers.
```java
eg.noArgs();
```
--------------------------------
### Using @MethodId Primitive Argument - Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Example of an event with a primitive argument, where the event is identified by a method ID.
```java
eg.withMethodId(150);
```
--------------------------------
### Creating Custom LongConverter
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/project-requirements.adoc
Provides a guide on creating custom `LongConverter` implementations for specialized conversion of `long` values during serialization and deserialization.
```java
import net.openhft.chronicle.wire.LongConversion;
import net.openhft.chronicle.wire.converter.LongConverter;
public class CustomLongConverter implements LongConverter {
@Override
public boolean parseLong(Object owner, long value) {
// Custom parsing logic
return true; // or false if not parsed
}
@Override
public void appendLong(Appendable app, long value) {
// Custom appending logic
}
}
// Usage:
@LongConversion(CustomLongConverter.class)
private long customValue;
```
--------------------------------
### One Scalar Primitive Argument - Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Example of sending an event with a single scalar primitive argument, such as a TimeUnit enum.
```java
eg.scalarArg(TimeUnit.DAYS);
```
--------------------------------
### NanoTimestampLongConverter Example
Source: https://github.com/openhft/chronicle-wire/blob/ea/README.adoc
Shows how to use the NanoTimestampLongConverter to parse a human-readable timestamp string into a long representation and convert it back. This converter is useful for storing precise timestamps efficiently.
```java
long ts = NanoTimestampLongConverter.INSTANCE.parse("2023-02-15T05:31:49.856123456");
System.out.println(ts); // 1676439109856123456
System.out.println(NanoTimestampLongConverter.INSTANCE.asString(ts)); // "2023-02-15T05:31:49.856123456"
```
--------------------------------
### Handling Schema Evolution in Binary Formats
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/adoc/project-requirements.adoc
Illustrates schema evolution in binary formats, where field numbers and names are used for identification. This allows for efficient handling of schema changes while maintaining compatibility.
--------------------------------
### Inline Comment Best Practices
Source: https://github.com/openhft/chronicle-wire/blob/ea/AGENTS.md
Demonstrates the difference between noise and valuable inline comments. Good comments explain subtleties or reasons not apparent from the code itself, while bad comments merely restate the obvious.
```java
// BAD: adds no value
int count; // the count
// GOOD: explains a subtlety
// count of messages pending flush
int count;
```
--------------------------------
### Event with Data Transfer Object - Java
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Example of sending an event containing a Data Transfer Object (DTO) with multiple fields of various types.
```java
eg.withDto(new MyTypes().b((byte) -1).s((short) 1111).f(1.28f).i(66666).d(1.01).text("hello world").ch('$').flag(true));
```
--------------------------------
### Create Iterator from Chronicle Queue
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/java/net/openhft/chronicle/wire/domestic/stream/README.adoc
This example demonstrates how to create a Java Iterator from a Chronicle Queue using the Streams utility. This allows integration with APIs that expect an Iterator.
```java
Iterator iterator = Streams.iterator(
```
--------------------------------
### Event with Data Transfer Object - Binary YAML
Source: https://github.com/openhft/chronicle-wire/blob/ea/EventsByMethod.adoc
Start of the binary representation for an event containing a DTO. Shows message length and event identifier.
```text
45 00 00 00 # msg-length
```
--------------------------------
### Extract MarketData Messages with Streams
Source: https://github.com/openhft/chronicle-wire/blob/ea/src/main/java/net/openhft/chronicle/wire/domestic/stream/README.adoc
Demonstrates how to create a Stream from a Chronicle Wire tailer and extract messages of a specific type (MarketData). This is a basic setup for iterating through messages.
```java
Streams.of(queue.createTailer(),
builder(MarketData.class).build())
```
--------------------------------
### Java: Method-Based Event Streaming with TextWire
Source: https://context7.com/openhft/chronicle-wire/llms.txt
Illustrates writing method calls as events using an interface and TextWire, then reading them back and dispatching them to an implementation. Requires Chronicle Wire core and bytes dependencies.
```java
import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.bytes.ByteBuffer;
import net.openhft.chronicle.wire.MethodReader;
import net.openhft.chronicle.wire.TextWire;
import net.openhft.chronicle.wire.Wire;
// Define event interface
interface Speaker {
void say(String message);
void volume(int level);
}
// Write method calls as events
Bytes bytes = Bytes.elasticByteBuffer();
Wire wire = new TextWire(bytes);
Speaker writer = wire.methodWriter(Speaker.class);
writer.say("Hello World");
writer.volume(80);
writer.say("Goodbye");
System.out.println(bytes);
// say: Hello World
// ---
// volume: !int 80
// ---
// say: Goodbye
// Read events back
class SpeakerImpl implements Speaker {
public void say(String message) {
System.out.println("Said: " + message);
}
public void volume(int level) {
System.out.println("Volume: " + level);
}
}
SpeakerImpl impl = new SpeakerImpl();
MethodReader reader = wire.methodReader(impl);
// Process each event
while (reader.readOne()) {
// Events automatically dispatched to impl
}
// Output:
// Said: Hello World
// Volume: 80
// Said: Goodbye
bys.releaseLast();
```