Introducing Dollar

I'm currently working on a new library called Dollar and I'd like to share some thoughts about it. It is pre-alpha software which means it's really in a prototyping state and the interfaces are not fixed yet.

If you like the ease of JavaScript, Ruby, Groovy etc. but also enjoy being able to work within the Java language then Dollar is for you. You can write typesafe code and then drop into typeless Dollar code whenever you need to. Dollar is both an alternative paradigm and a complementary resource.

Show me the code!

So let's create some JSON in Java:

1
2
3
4
5
6
7
8
9
10
var profile = $(
$("name", "Neil"),
$("age", new Date().getYear() + 1900 - 1970),
$("gender", "male"),
$("projects", $jsonArray("snapito", "dollar")),
$("location",
$("city", "brighton"),
$("postcode", "bn1 6jj"),
$("number", 343)
));

As you can see, creating nested JSON data is incredibly easy.

And then we can query that JSON using Dollar, in much the same way you would in jQuery.

1
String name = profile.$("name").$$();

Or we can do queries using JavaScript (Nashorn) expressions ($ means the current value).

1
2
profile.$("$['age']/11").$int()
profile.$("$.gender").$()

We can also create our objects from JSON Strings ...

1
$("{\"name\":\"Dave\"}").$("name").$$()

Lists ...

1
2
list = $list("Neil", "Dimple", "Charlie");
assertEquals(list, $list("Neil").add("Dimple").add("Charlie"));

Or maps ...

1
2
3
4
5
6
Map map = new HashMap();
map.put("foo", "bar");
Map submap = new HashMap();
submap.put("thing", 1);
map.put("sub", submap);
assertEquals(1, $(map).$("sub").$map().get("thing"));

Dollar has built in support for being a webserver (using Spark):

1
2
//Serve up the request headers as a JSON object under the /headers URL
$GET("/headers", (context) -> context.headers());

And also supports queues:

1
2
profile.push("test.profile");
var deser = profile.pop("test.profile", 10 * 1000);

... persistence ...

1
2
3
assertTrue(profile.save("test.profile.set").equals(profile));
var deser = profile.load("test.profile.set");
Assert.assertEquals(deser.$$(), profile.$$());

... and pub/sub.

1
2
3
4
5
6
7
8
9
final int[] received = {0};
Sub sub = $sub((message) -> {
received[0]++;
}, "test.pub");
sub.await();
profile.pub("test.pub");
Thread.sleep(100);
sub.cancel();
assertEquals(1, received[0]);

Want to give it a spin, why not spin up and play with Dollar on Terminal.com

Read More