Burning the Midnight Oil

Research, personal interests, life and all the pretty stuff in between

Starting JADE (Java Agent Dev Framework) via C++ using JNI

leave a comment »


I figured I’d post my solution to this since the questing has been asked around the web but no actual code has been posted. Essentially you want to:

Step 1: Create a static method within your Java class to instantiate a JADE container.
Step 2: Create a native method to retrieve/create the Java Virtual Machine (JVM) for JADE to live in.
Step 3: Create a native method to invoke the static method in the JAR compiled from step 1 using the JVM from step 2.

Step 1

The official JADE book sheds some light on how to create a JADE container within Java. This short function does the trick:

//Java
  public static boolean startJadePlatform()
    {
        try{
        jade.core.Runtime rt = jade.core.Runtime.instance();
        Profile p = new ProfileImpl();
        container = rt.createMainContainer(p);
        
        }catch(Exception ex)
        {
            Logger.getLogger(PlatformMediator.class.getName()).log(Level.SEVERE, null, ex);
        }
        return (container != null);
    }

Step 2

On the C++ side, I decided to separate my code in two functions. My first function simply creates a java virtual machine to work with. I follow the indications from this post for most of the details.

//C++
JavaVM* startJVM()
{
	/***	Finding the jvm.dll	***/
	DWORD retval;
	HKEY jKey;	// fetch jvm.dll path from registry
	if (retval = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\JavaSoft\\Java Runtime Environment"), 0, KEY_READ, &jKey))
	{
		RegCloseKey(jKey);
		//manage exception
	}

	TCHAR versionString[16]; // version no. => 16 chars
	DWORD bufsize = 16 * sizeof(TCHAR);
	if (retval = RegGetValue(jKey, NULL, TEXT("CurrentVersion"), RRF_RT_REG_SZ, NULL, versionString, &bufsize))
	{
		RegCloseKey(jKey);
		//manage exception
	}

	dllpath = new TCHAR[512];
	bufsize = 512 * sizeof(TCHAR);
	retval = RegGetValue(jKey, versionString, TEXT("RuntimeLib"), RRF_RT_REG_SZ, NULL, dllpath, &bufsize);
	RegCloseKey(jKey);
	if (retval)
	{
		delete[] dllpath;
		//manage exception
	}

	/***	Loading the jvm.dll and functions GetCreatedJavaVMs & CreateJavaVM ***/

	HMODULE jniModule = LoadLibraryA(dllpath);

	delete[] dllpath;
	if (jniModule == NULL)
		return NULL;

	typedef int (JNICALL * JNI_CreateJavaVM)(JavaVM** jvm, JNIEnv** env, JavaVMInitArgs* initargs);
	JNI_CreateJavaVM createJavaVM = (JNI_CreateJavaVM)GetProcAddress(jniModule, "JNI_CreateJavaVM");

	/*** Creating the JVM ***/
	JavaVMInitArgs initArgs;

	JavaVMOption* options = new JavaVMOption[4]; 
	options[0].optionString = "-Djava.compiler=NONE";           /* disable JIT */
	options[1].optionString = "-Djava.class.path=C:\\Users\\you\\yourproject\\dist\\yourjar.jar";	
	options[2].optionString = "-Djava.library.path=c:\\yourlibraries";  /* set native library path */
	options[3].optionString = "-verbose:jni";                   /* print JNI-related messages */

	initArgs.version = JNI_VERSION_1_6;
	initArgs.nOptions = 4;
	initArgs.options = options;
	initArgs.ignoreUnrecognized = false;

	JavaVM* jvm;
	JNIEnv* env;

	typedef jint (JNICALL * GetCreatedJavaVMs)(JavaVM**, jsize, jsize*);
	GetCreatedJavaVMs JNI_GetCreatedJavaVMs;

	JNI_GetCreatedJavaVMs = (GetCreatedJavaVMs)GetProcAddress(jniModule, "JNI_GetCreatedJavaVMs");

	int n;
	retval = JNI_GetCreatedJavaVMs(&jvm,1, (jsize*) &n);

	if (retval == JNI_OK)
	{
		if (n == 0)
		{
			retval = createJavaVM(&jvm, &env, &initArgs);	//create new
		}else
		{
			if (n != 1)
			{
				return NULL;
			}
		}
	}
	return jvm;
}

With that done, your C++ method can already be used to create or fetch a JavaVM instance. You must keep the pointer to the JVM as is the only way to access the JNIEnv between calls.

Step 3

Invoking the JAR functionality doesn’t require much effort. I passed the JavaVM as argument, but there are other alternatives.

//C++
int Environment::startPlatform(JavaVM* jvm){

	JNIEnv* env;
	bool mustDetach = false;

	jint retval = jvm->GetEnv((void**)&env, JNI_VERSION_1_6);
	if (retval == JNI_EDETACHED)
	{
		JavaVMAttachArgs args;
		args.version = JNI_VERSION_1_6;
		args.name = NULL;
		args.group = NULL;
		retval = jvm->AttachCurrentThread((void **)&env, &args);
		mustDetach = true; 
	}
	if (retval != JNI_OK)
		throw retval;

	if (retval == JNI_OK)
	{

		static const char* const jvmClassName = "com/namespace/to/class/Platform";

		jclass clazz =  env->FindClass(jvmClassName);
		if (env->ExceptionCheck())
		{
			env->ExceptionOccurred();
			return JNI_ERR;
		}
		if (clazz == NULL){
			return JNI_ERR;
		}

		jmethodID mid = env->GetStaticMethodID(clazz, "startJadePlatform", "()Z");	//determine signature via javap -s
		if (mid == NULL){
			return JNI_ERR;
		}

		BOOL returnedValue = env->CallStaticBooleanMethod(clazz, mid);

		if (mustDetach)
		{
			jvm->DetachCurrentThread();
		}

		if (returnedValue) return JNI_OK;
		return JNI_ERR;
	}

With this in place, you can call both functions sequentially (passing the respective parameters) and the JADE platform will be initiated within the JavaVM. This implementation checks for existing instances of JavaVM, therefore is safe to use between multiple callbacks and different threads. If you need to set up your environment from scratch or have little knowledge of JNI, these references (1, 2) were very handy.

Good luck!

Written by cd

April 29, 2014 at 10:04 am

Posted in C++, Code, Java, Research

Tagged with , , , , , ,

▶ Denzel Washington On Failure

leave a comment »

Written by cd

August 20, 2013 at 1:17 pm

Formatting Optimization Problems with LaTeX | JC Notes

leave a comment »

\usepackage{amsmath}

\begin{equation*}
\begin{aligned}
& \underset{x}{\text{minimize}}
& & f_0(x) \\
& \text{subject to}
& & f_i(x) \leq b_i, \; i = 1, \ldots, m.
\end{aligned}
\end{equation*}

produces:

\begin{aligned}  & \underset{x}{\text{minimize}}  & & f_0(x) \\  & \text{subject to}  & & f_i(x) \leq b_i, \; i = 1, \ldots, m.  \end{aligned}

Extracted from Formatting Optimization Problems with LaTeX | JC Notes.

Written by cd

August 14, 2013 at 5:28 am

Posted in LaTeX tips

Tagged with , ,

Building a Question Board Web app with Meteor

leave a comment »

I just finished this tutorial, a little hard to follow but well worth doing. Meteor is really impressive! Hopefully version 1.0 will be out soon.

Deployed on http://question-board.meteor.com

Source code  https://github.com/cdario/question-board

Written by cd

August 9, 2013 at 1:55 pm

My top 3 LaTeX Environments: Notepad++, ShareLaTeX, and Sublime Text

leave a comment »

Not long ago setting up a LaTeX environment was painfully hard as a non-Linux user. Recently, I’ve found myself spending more time in my Ubuntu machine and have started to appreciate its simplicity when it comes to writing. Hardcore Linux users may prefer something like emacs as a LaTeX editor, even tough l started to use it frequently, still find a bit difficult when it comes to Latex.

Since I’m still bound to go back to Windows, I’ve decided to write this post about my three preferred LaTex Environments for Linux, Windows and the Web.

For Windows, Notepad++:

I’ve already been using several specific editors for quite some a while. In the end, none provided the simplicity and customisation I wanted, until I found Notepad++. It is a very simple, extremely efficient text editor with an impressive arsenal of bindings, tweaks and settings to suit any need you may have.

Pros:

  • Extremely flexible and lightweight
  • Full-screen and post-it mode ( quite necessary these days )
  • Allows custom UI and key bindings ( probably need a while to figure them all)
  • Advanced syntax highlight ( not only for LaTeX obviously)

Cons:

  • Requires time to setup to your needs and extend to LaTeX. This post was helpful
  • No cloud or auto-save features included natively (you could just use dropbox for that)
  • Doesn’t include a PDF previewer (If you mind for that, you need a non-blocking viewer like SumatraPDF)

On the Web, ShareLaTeX :

This is a relatively new project (but not the only one) on a web-based collaborative LaTeX specific editor. I joined since very early and been recommending it often, mainly because it takes from you the burden of setting up an environment (the main reason for Win users to find LaTeX tedious), you just need to open an account and you’re good to go, libraries are already included and even has some templates to get you writing. The main advantage of ShareLaTeX is, as it names implies, the collaborative twist it has. I use it to distribute my latest version by keeping the document public and non-editable (not everyone wants to open another account just to preview and edit the document) – collaborators can just get a copy, edit it and send their updates, then you merge the copies and update the shared version.

Image

Pros:

  • Safely stores your documents on the cloud and auto-save included
  • Access to few handy templates ( I rather use my own, though)
  • The editor can be themed, but I found the highlighting not as good as others
  • Share the project (several files) with others via link (public or private)
  • Chat functionality ( I haven’t really used that but good to have it)
  • Each project includes a huge LaTeX scripts library! But you can still add your own in case is not already included .
  • Will allow Dropbox syncs for premium users

Cons:

  • The editor still feels a bit awkward, even collapsing the panels and going full screen doesn’t give you a comfy, isolated writing environment.
  • Multi screen support for editor and output PDF ( but you can actually open a separate window with the same project)
  • Key shortcuts might be a good idea as I dislike clicking to preview
  • You need an Internet connection to access your projects. This is a problem if you really need to cut all distractions and temptations.

For Linux, Sublime Text :

This editor excels in all categories. It has a really smooth, minimalistic interface that can be configured in almost any possible way. It is very slick and you have access not only to a million keyboard shortcuts but also a plug-in browser within the editor itself. This is probably my first choice for LaTeX. The software is also available for Windows and MacOS. It features a minimap that allows you to move with ease, but if you need total isolation you can try the distraction free mode. It seems well documented and so far, I’ve found posts on any modification I wanted to do.

Image

Pros:

  • Slick and fully customizable experience
  • Tons of keyboard shortcuts and simple compiler configuration (using Latex Tools plug-in)
  • Embedded plug-in market where you can get utilities such as reference management, auto-completion  and more
  • Nice highlighting system and theming included
  • The free-distraction mode is simply perfect
  • Native spell-checker included
  • The snippet tool and command palette are pretty nifty

Cons:

  • It has a very steep licence price you can, however, use Sublime2 for free (with a few pop ups from time to time). A more comprehensive pricing scheme would be great.
  • Many of the most impressive features have to be installed separately and some of them aren’t free.

To conclude, my top 3 LaTeX environment share certain features such as responsiveness, flexibility and coding experience overall. Some other features like auto-completion and version management are not as important to me. If you find yourself using LaTeX a lot and not feeling comfortable with your current editor there are plenty of options now to choose from.

Written by cd

August 9, 2013 at 7:32 am

LaTex: Power combo

leave a comment »

If you still wondering whether you need to use LaTex, take a look at this article . Many websites provide detailed information on how to install and use LaTex, but since I was looking for a concise source, I decided to put here my configuration (one of many), and a simplified step-by-step to get LaTex running. I will focus in what to get, how to install and how to create a simple document from a template in Windows7. You need:

After installing the software, open TeXworks and then File > New From Template > Basic LaTex documents > article. This will open a new document which you must save and then compile by clicking the green button in the toolbar (with pdfLaTex selected in the dropdown). If everything goes fine and after a few lines in the console output the TeXworks viewer will pop out with your output PDF. That is pretty much to it. Sumatra PDF allows you to edit and recompile (in TeXworks) without closing the file which is not the case for other PDF Readers.

When things go wrong…

One common issue with this setup is the use of mismatching versions of MiKTex  and TeXworks templates. This can be easily fixed by accessing All Programs > MiKTex x.x. > Maintenance(Admin) > Update and running the wizard. More on formatting with LaTex and reference use later .

 

Written by cd

September 13, 2011 at 6:40 am

What is a review article and where do I get one?

leave a comment »

Research Bar

Research Bar (Photo credit: Rice-Aron Library)

There is a sea of research publications out there. Might seem overwhelming to start research in a new area or simply catch up with current trends in a particular field. A good starting point are research articles. These are compilations of  works on a specific topic, field or discipline. Relevant and recent articles are preferred and the value added from this type of publications is the structure and comprehensiveness of the materials.

A review article is the perfect place to glance at the state of art of your discipline, find interesting research questions or quickly gather important references such as key publications and authors. Many journals mark these articles, thus making things easier for us users.

If you are looking for scientific publications, you can find review articles with Scopus using the following simple steps:

  1. Type some relevant terms in the search box. Be as specific as possible.
  2. Set document type to “Review”
  3. Add other appropriate filters (dates, disciplines, etc.)
  4. Arrange the results list based on your preferences (No. of citations, date, etc.)
You may need to tune you query up to find the best term combinations. Also, you still need to verify the publication quality and check for similar options in other portals. Finding that key paper is a difficult task, however this sort of publications are extremely useful in giving insight of new or rapidly changing areas.
%d bloggers like this: