What I've got to say @astolwijk

About me

I am a Dutch Web and MooTools Developer and I create Websites and WebApps.

I'm also an Embedded Systems student at the TU Delft.

You can find me at other cool places too, like twitter or github.

github.com/arian

ReactJS in Java Hello World

ReactJS is becoming a hugely popular solution for building complex Web Applications. It is so nice to use because it really resembles building applications like you used to in the good old PHP days a long time ago, where you construct the HTML once on the server, and be done with it. Don't think about changing state over time, just render once, and refresh once the data changed.

ReactJS runs entirely in the Browser. You give the components data, and it constructs the DOM for you. This means that your initial page can be as simple as:

<!DOCTYPE>
<html>
<head><title>ReactJS Page</title></head>
<body><div id="app"></div></body>
<script>
React.render(MyComponent(), document.getElementById("app"));
</script>
<html>

Considering the first principle of Guillermo Rauch's 7 Principles of Rich Web Applictions:

"Server rendered pages are not optional"

And the tl;DR

"Server rendering is not about SEO, it's about performance. Consider the additional roundtrips to get scripts, styles, and subsequent API requests. In the future, considering HTTP 2.0 PUSH of resources."

So we need to pre-render the DOM on the server too.

Fortunately this is really easy with ReactJS, using the React.renderToString function. It's exactly like the React.render function, except rendering it to in a DOM node, it returns a string. The HTML in that string contains data-react-* attributes, so if you React.render on the client-side again, it picks up the DOM that is already there and only applies the actual changes. It takes the string as initial DOM state.

The thing with ReactJS, however, or with any client-side rendering engine, is that it's written in JavaScript. That makes sense because usually it's used on the client side. With NodeJS we have this amazing server-side runtime that can run JavaScript on the server. So the usual option would be to use NodeJS to run ReactJS to generate the server-side HTML.

The downside of NodeJS is that not every server configuration has NodeJS easily available. For example a lot of servers use Ruby, Python, Java or PHP.

There are two options: run NodeJS as a "render service" or use an embedded JavaScript runtime which is possible with Java.

NodeJS as local Render Service

One option would be to run a NodeJS process on your server, and use an internal port or Unix Socket to render the ReactJS components with NodeJS and use the result in the original stack.

var http = require('http');
var parse = require('url').parse;
var React = require('react');
var MyComponent = React.createClass({
render: function() {
return React.DOM.div(null, this.props.text);
}
});
var server = http.createServer(function(req, res) {
var text = parse(req.url, true).query.text || 'hello world';
var html = React.renderToString(React.createFactory(MyComponent)({text: text}));
res.end(html);
});
server.listen(3000);

And then your original code, for example your Python 3 server, can use this very simple snippet to render the ReactJS component with NodeJS as service:

import http.client
conn = http.client.HTTPConnection("localhost:3000")
conn.request("GET", "/?text=bar")
r1 = conn.getresponse()
print(r1.status, r1.reason)
print(r1.read())

The downside of this approach is that you have to send your data from your program through a TCP port or a Unix Socket.

ReactJS with the Embedded JS Runtime in Java

Java has an embedded JavaScript runtime already for a long time. First there was Rhino, and now, since Java 8, there is Nashorn. In Java you have an entire JavaScript runtime at your disposal. The simple Nashorn Hello World looks something like this, directly taken from the Nashorn website at Oracle:

package sample1;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Hello {
public static void main(String... args) throws Throwable {
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
engine.eval("function sum(a, b) { return a + b; }");
System.out.println(engine.eval("sum(1, 2);"));
}
}

As it turns out is is relatively easy to run ReactJS in Java, as shown here:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
public class Test {
private ScriptEngine se;
// Constructor, sets up React and the Component
public Test() throws Throwable {
ScriptEngineManager sem = new ScriptEngineManager();
se = sem.getEngineByName("nashorn");
// React depends on the "global" variable
se.eval("var global = this");
// eval react.js
se.eval(new FileReader("node_modules/react/dist/react.js"));
// This would also be an external JS file
String component =
"var MyComponent = React.createClass({" +
" render: function() {" +
" return React.DOM.div(null, this.props.text)" +
" }" +
"});";
se.eval(component);
}
// Render the component, which can be called multiple times
public void render(String text) throws Throwable {
String render =
"React.renderToString(React.createFactory(MyComponent)({" +
// using JSONObject here would be cleaner obviosuly
" text: '" + text + "'" +
"}))";
System.out.println(se.eval(render));
}
public static void main(String... args) throws Throwable {
Test test = new Test();
test.render("hello");
test.render("hello world");
}
}

As shown above, there are two approaches that make loading the initial page load, with pre-rendered ReactJS components on the Server super fast, as the browser has to do less, and you don't need an initial Ajax request for your initial data. The NodeJS solution is very flexible, as it can be used for any programming language, but it requires running a NodeJS process along your normal server. If you're using Java, or anything that runs on the JVM (Java, Scala, Clojure, JRuby, etc.) you can use the embedded version. Finally thanks to ReactJS, it perfectly consumes your server-generated DOM structure, so after updates, it just updates the difference, which makes it a very fluid and easy to program solution!

Tree Traversal, Depth first and Breadth first in Haskell

Lately I'm really digging Functional Programming, and especially Haskell. I've been reading Real World Haskell, which is a very nice free book about Haskell.

Today I was wondering what Breadth First traversal was. Of course I should know this and it's stupid I forgot. To make sure I wouldn't forget in the future I made a little exercise to improve my Haskell skills, and to make sure I wouldn't forget the Breadth First algorithm anymore.

Dynamic disassembling instructions with ptrace and udis86 for timing analysis

For a University assignment for a course called Real-Time Systems we had to implement a prototype for timing analysis by tracing instructions.

The idea is that when executing a program, ptrace controls the execution and stops after each instruction. After this the actual instruction in the memory can be fetched. Knowing which instruction is executed you could associate this with a certain time, add all times together for each instruction and you could dynamically determine how long a program would run: profit!

I made a prototype that can be viewed on GitHub.

Setting up a MySQL database

This post is just for future reference with a few MySQL commands I can't really remember yet for creating a new database and mysql user. Probably now I posted them here, I will remember them ;). So it might be interesting or less interesting for you.

First, login as root with:

mysql -u root -p

If you forgot your root password, follow these steps:

sudo service mysql stop
sudo mysqld --skip-grant-tables &
mysql -u root mysql
mysql> UPDATE user SET Password=PASSWORD('YOURNEWPASSWORD') WHERE User='root';
mysql> FLUSH PRIVILEGES; exit;

When logged in, create a new database:

CREATE DATABASE databasename;

And create a user for it, if we want a separate user at least:

GRANT ALL ON databasename.* TO myuser@localhost IDENTIFIED BY 'mypassword';

And that's usually what you need to know.

Reactive Programming

Most programming languages or techniques nowadays are sequential. When executing a statement c = a + b, c is the result of the addition of the current values of a and b. If either one of those variables change their value, c is not changed.

var a = 5;
var b = 10;
var c = a + b;
console.log(c); // logs 15
a = 20;
console.log(c); // still logs 15

I have a Blog!

Usually I don't have too strong feelings about certain topics. Still, I wanted to create a place where I can write about stuff, when I've created something on GitHub or some other in-dept blogpost. I've written on the MooTools Blog but sometimes I'd like to write about something else. Don't expect lots of posts, I'm not a David Walsh ;).

I have a healthy hate for WordPress, and I wanted something simple, so a static blog generator would be really cool, especially if it's written in Node. Some people think it wouldn't be even interesting if it wasn't written in Node or Lua. So this blog is generated by a static blog generator called hexo. I tried a few, but this mostly just worked. It uses Stylus for CSS and ejs for templating, which is really nice. I could've made my own, but hey, sometimes it's just better to use something what's already there.

I wanted to keep my homepage however. This shows my latest tweets and latest updated GitHub repositories. This was written already in PHP, running on very cheap-ass shared hosting, so I made a little script that it generates an index.php file, which actually isn't static.

Like with a lot of my work, I just put this blog on GitHub, so if you see a typo, you don't have to put it in the comments, but you can send me a pull request!

Some remarkable facts during the production of this blog:

  • I used two spaces!
  • For the bit JS I wrote, I used ) { instead of ){.
  • FTP for "deployment" feels so good.
  • All semicolons are nicely placed after each line of JavaScript.
  • Look Ma, Responsive Design!!11!