Using Java to call an Erlang function - nickmcdowall/Erlang-Examples GitHub Wiki

Create an Erlang module with a function that will be invoked by Java:

-module(translator).
-export([translate/2]).

translate(Word, Language) ->
	case Language of
		'Spanish' -> spanish(Word)
	end.
	
spanish(Word) ->
	case Word of
		'friend' -> 'amigo'
	end.

Start an Erlang node called 'server' with a cookie value of 'batman':

c:\Dev\Erlang-Examples\src>erl -sname server -setcookie batman
Eshell V5.9.1  (abort with ^G)
(server@Nick-HP)1>

Compile the translator module:

(server@Nick-HP)1> c(translator).
{ok,translator}
(server@Nick-HP)2>

Create a Java class that will connect to the Erlang node and invoke the function. You will need to add the JInterface library that ships with an Erlang OTP distribution to the build path. This can be found under the lib folder (e.g. C:\Program Files\erl5.9.1\lib\jinterface-1.5.6\priv\OtpErlang.jar). Here is a JUnit test that calls the running erlang node:

import com.ericsson.otp.erlang.OtpSelf;
...

public class TranslatorTest {

	private OtpSelf client;
	private OtpPeer server;
	private OtpConnection connection;

	@Before
	public void init() throws IOException, OtpAuthException {
		client = new OtpSelf("client", "batman");
		server = new OtpPeer("server@Nick-HP");
		connection = client.connect(server);
	}

	@Test
	public void shouldInvokeErlangTranslateFunction() throws IOException,
			OtpAuthException, OtpErlangExit, OtpErlangDecodeException {
		
		connection.sendRPC("translator", "translate", withArgs("friend", "Spanish"));
		OtpErlangObject response = connection.receiveMsg().getMsg();
		assertTrue(response.toString().contains("amigo"));
	}

	private OtpErlangObject[] withArgs(String word, String language) {
		return new OtpErlangObject[] { 
				new OtpErlangAtom(word),
				new OtpErlangAtom(language) 
		};
	}
}

Notice that the cookie value used when constructing OtpSelf must match what was used when starting the Erlang node ('batman'). The Erlang node name can be found by running node(). in the Erlang shell.