Skip to content

Commit

Permalink
[Java] JSON for Message Payloads (#254)
Browse files Browse the repository at this point in the history
Signed-off-by: Maurice van Veen <github@mauricevanveen.com>
  • Loading branch information
MauriceVanVeen authored Aug 8, 2024
1 parent 04f16fc commit d3496e9
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
3 changes: 3 additions & 0 deletions docker/java/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ dependencies {
implementation 'io.nats:jnats-json:2.0.0'
implementation 'io.nats:jwt-java:2.0.0'
implementation 'io.nats:jnats:2.19.2-SNAPSHOT'

// JSON serialization/deserialization
implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2'
}

apply plugin: 'java'
Expand Down
94 changes: 94 additions & 0 deletions examples/messaging/json/java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package example;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.nats.client.Connection;
import io.nats.client.Nats;
import io.nats.client.Dispatcher;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;

public class Main {

public static void main(String[] args) {
String natsURL = System.getenv("NATS_URL");
if (natsURL == null) {
natsURL = "nats://127.0.0.1:4222";
}

// Initialize a connection to the server. The connection is AutoCloseable
// on exit.
try (Connection nc = Nats.connect(natsURL)) {

// Construct a payload and serialize it.
// Using Jackson in this example, but any other JSON library can be used as well
// (and even any other message format since the payload is just bytes).
ObjectMapper objectMapper = new ObjectMapper();
Payload payload = new Payload("bar", 27);
byte[] messageBytes = objectMapper.writeValueAsBytes(payload);

CountDownLatch latch = new CountDownLatch(2);

// Create a message dispatcher for handling messages in a
// separate thread and then subscribe to the target subject.
Dispatcher dispatcher = nc.createDispatcher((msg) -> {

// Attempt to deserialize the payload.
// If deserialization fails, alternate handling can be performed.
try {
Payload deserializedPayload = objectMapper.readValue(msg.getData(), Payload.class);

System.out.printf("received valid JSON payload: %s\n", deserializedPayload);
} catch (IOException e) {
System.out.printf("received invalid JSON payload: %s\n",
new String(msg.getData(), StandardCharsets.UTF_8));
} finally {
latch.countDown();
}
});

dispatcher.subscribe("foo");

// Publish the serialized payload.
nc.publish("foo", messageBytes);
nc.publish("foo", "not json".getBytes(StandardCharsets.UTF_8));

// Await the dispatcher thread to have received all the messages before the program quits.
latch.await();

} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}

class Payload {
private final String foo;
private final int bar;

@JsonCreator
Payload(@JsonProperty("foo") String foo,
@JsonProperty("bar") int bar) {
this.foo = foo;
this.bar = bar;
}

public String getFoo() {
return foo;
}

public int getBar() {
return bar;
}

@Override
public String toString() {
return "Payload{" +
"foo='" + foo + '\'' +
", bar=" + bar +
'}';
}
}

1 comment on commit d3496e9

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deploy preview for nats-by-example ready!

✅ Preview
https://nats-by-example-h1qximk9u-connecteverything.vercel.app

Built with commit d3496e9.
This pull request is being automatically deployed with vercel-action

Please # to comment.