Starting JADE (Java Agent Dev Framework) via C++ using JNI
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!
Formatting Optimization Problems with LaTeX | JC Notes
\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:
Extracted from Formatting Optimization Problems with LaTeX | JC Notes.
Building a Question Board Web app with Meteor
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
My top 3 LaTeX Environments: Notepad++, ShareLaTeX, and Sublime Text
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.
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.
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.
LaTex: Power combo
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:
- MiKTex: The compiler
- TeXworks: The editor
- Sumartra PDF: The reader
When things go wrong…
Moving from EndNote to Mendeley
After looking around for alternatives to Endnote I found that ,fortunately, there are plenty of options. Maybe the most mature and complete out there are Reference manager, the open source JabRef and the newcomer Mendeley. Refman didn’t impress me at all. The interface could be much better. On the other hand, I was greatly surprised by JabRef, a good piece of free software IMHO. It does the work well, provides a simple color code to help you keep your records detailed and, if you are an MS Office user like myself (sometimes) you can find some really nice utilities (i.e. Bibtex4Word) to help your writing/citing cycle. The only issue with JabRef: the project has been inactive since 2009.
Frankly, I did not expect too much from Mendeley. At the beginning, it looked to me like a toy application, and surely you do not want to play with your precious references. Just to be fair, I gave it a try. It really blows your mind! Very simplistic. They provide a desktop application that really makes things easier. In less than 10 minutes I had my EndNote library fully working in Mendeley. The drag and drop was a feature I needed desperately. Also, the convenient look-up in the upper corner, helps you speed things up. Plus all the other usual stuff, on-line backup, categories and being able to use multiple formats. On top of that, you get something completely unexpected: Social networking. After setting up your profile on the Web, you can access interest groups and collaborate, share and discuss ideas or simply share the references with the world. I am not completely sure, how social do I want to go with my work, however, is a nice thing to have the option. Other goodies included in Mendeley desktop: Embedded PDF reader, link between the actual file and the reference, and obviously support to embed references in your MS Word or Latex Documents. If you use other services, such as Zotero or Citeulike the application handles the transition well.
Seems like Thomson Reuters are finally out of the market of reference management. I still need to test most of the functionalities, but will be using it as my only RM from now on. Happy citations!
Searching for a reference manager
Once again, Microsoft Word has crashed in my computer after trying to edit a reference from Endnote. I’ve already uninstalled it, and Word went back to normal. Now, I am facing the dilemma of finding an efficient way to collect and use my references. These are my options:
- Try other reference managers (as refman.com)
- Give another try to Latex (and Bibtex.org)
- Use the reference system included in Office Word (Which have been using for a year)
Seems like a workaround for the Word2010/endnote issue won’t be here soon according to this guys. Would be good to have some ideas about this, I’ve seen other people organizing their references in files which I think is completely tedious and keeps you away from doing real work (as reading your references!).
More thoughts on this soon.
HLA and OpenSource
I’m looking at HLA (High Level Architecture) again. After a couple of months, I decided to give it a second try. First thing, find a mature open source implementation. Luckily, found poRTIco that looks stable. The developers seem willing to help via forum.
Some theory on HLA here.