jni binding, javac error, unexpected token - java

We did an openvr java binding using jna and it's true what they usually say about jna, it's quite easy to implement.
On the contrary, it has some performance penalties. Googling around and reading some papers, jna is from 10 to almost 80 times slower than jni (here and here).
This wouldn't be a problem for not-critical performance scenarios, but we run into some performance issues and we are trying to addresses all the causes, such as the binding for example.
I searched for some time and there are a lot of different ways to achieve this, but given the header we'd like to port is relatively easy (last famous words..) we are trying to do it manually.
I started by the two most important calls, VR_Init and VR_ShutDown:
inline IVRSystem *VR_Init( EVRInitError *peError, EVRApplicationType eApplicationType )
{
IVRSystem *pVRSystem = nullptr;
EVRInitError eError;
VRToken() = VR_InitInternal( &eError, eApplicationType );
COpenVRContext &ctx = OpenVRInternal_ModuleContext();
ctx.Clear();
if ( eError == VRInitError_None )
{
if ( VR_IsInterfaceVersionValid( IVRSystem_Version ) )
{
pVRSystem = VRSystem();
}
else
{
VR_ShutdownInternal();
eError = VRInitError_Init_InterfaceNotFound;
}
}
if ( peError )
*peError = eError;
return pVRSystem;
}
/** unloads vrclient.dll. Any interface pointers from the interface are
* invalid after this point */
inline void VR_Shutdown()
{
VR_ShutdownInternal();
}
The corresponding java class is pretty simple:
public class HelloVr {
static {
System.loadLibrary("openvr_api");
}
static final int VRInitError_None = 0, VRApplication_Scene = 1;
public native IVRSystem VR_Init(ByteBuffer peError, int eApplicationType);
public native void VR_Shutdown();
public static void main(String[] args) {
new HelloVr();
}
public HelloVr() {
ByteBuffer peError = ByteBuffer.allocateDirect(Integer.BYTES).order(ByteOrder.nativeOrder());
IVRSystem hmd = VR_Init(peError, VRApplication_Scene);
System.out.println("error: " + peError.getInt(0));
}
class IVRSystem {
private long nativePtr = 0L;
}
}
Now is time to compile HelloVr.java into HelloVr.class by typing
javac HelloVr.java
But I get Unexpected Token:
PS C:\Users\GBarbieri\Documents\NetBeansProjects\Test\Test\src\test> "C:\Program Files\Java\jdk1.8.0_102\bin\javac.exe"
.\HelloVr.java
Unerwartetes Token ".\HelloVr.java" im Ausdruck oder in der Anweisung.
Bei Zeile:1 Zeichen:66
+ "C:\Program Files\Java\jdk1.8.0_102\bin\javac.exe" .\HelloVr.java <<<<
+ CategoryInfo : ParserError: (.\HelloVr.java:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
why?

Not exactly the ideal answer I was looking for, but it made it working.
I added the javac.exe directly to the PATH environment variable and simply run:
javac HelloVr.java

Related

Automatically handling / ignoring NameError in Jython

I have a setup where I execute jython scripts from a Java application. The java application feed the jython script with variables, coming from the command line, so that a user can write the following code in it's jython script:
print("Hello, %s" % foobar)
And will call the java program with this:
$ java -jar myengine.jar script.py --foobar=baz
Hello, baz
My java application parse the command-line, and create a variable of that name with the given value to give to the jython scripting environment to consume. All is well so far.
My issue is that when the user does not provide the foobar command-line parameter, I'd like to be able to easily provide a fallback in my script. For now, the user needs to write that sort of code to handle the situation where the foobar parameter is missing from the command-line:
try: foobar
except NameError: foobar = "some default value"
But this is cumbersome, especially if the number of parameters is growing. Is there a way to handle that better from the script user point of view?
I was thinking of catching the jython NameError in the Java code, initializing the variable causing the exception to a default value if the variable causing the exception "looks like" a parameter (adding a naming convention is OK), and restarting where the exception occurred. Alternatively, I can require the script user to write code such as this:
parameter(foobar, "some default value")
Or something equivalent.
Well, this is one ugly workaround I found so far. Be careful, as this will call the script in loop many times, and is O(n^2).
private void callScriptLoop(String scriptfile) {
PythonInterpreter pi = new PythonInterpreter();
pi.set("env", someEnv);
int nloop = 0;
boolean shouldRestart;
do {
shouldRestart = false;
try {
pi.execfile(scriptfile);
} catch (Throwable e) {
if (e instanceof PyException) {
PyException pe = (PyException) e;
String typ = pe.type.toString();
String val = pe.value.toString();
Matcher m = Pattern.compile("^name '(.*)' is not defined")
.matcher(val);
if (typ.equals("<type 'exceptions.NameError'>")
&& m.find()) {
String varname = m.group(1);
pi.set(varname, Py.None);
System.out.println(
"Initializing missing parameter '"
+ varname + "' to default value (None).");
shouldRestart = true;
nloop++;
if (nloop > 100)
throw new RuntimeException(
"NameError handler infinite loop detected: bailing-out.");
}
}
if (!shouldRestart)
throw e;
}
} while (shouldRestart);
}

How to solve lua errors: "attempt to index ? (a nil value)" [duplicate]

This question already has an answer here:
Attempt to index local 'v' (a nil value)
(1 answer)
Closed 5 years ago.
There has been a lot of post about this kind of error and most people say it is related to table and array indexing problems. But I am not using tables at all, I am just trying to call a library function I made and I get this error. Here is the lua script called from java:
String script = new String (
"function event_touch ( )"
+ " pb.open_form ('view_monster');"
+ " print ('I ran the lua script');"
+ "end");
PBLUAengine.run_script(script, "event_touch");
This gives me the following error when trapping the exception:
"function event_touch ( ) pb.open_form ('view_monster'); print ('I ran the lua script');end:1 attempt to index ? (a nil value)"
The run_script() function calls the script like this( I am using luaj):
public static LuaValue run_script ( String script )
{
try
{
LuaValue chunk = s_globals.load( script );
return chunk.call();
}
catch ( Exception e)
{
Gdx.app.error ("PBLUAengine.run_script()", e.getMessage() );
}
return null;
}
The library method goes like this and the same piece of code works when called from java:
static class open_form extends OneArgFunction
{
public LuaValue call (LuaValue formname)
{
String tmpstr = (String ) CoerceLuaToJava.coerce(formname, java.lang.String.class );
try
{
PBscreen_game.hide_subscreen(PBscreen_game.MENU_SUBS);
PBscreen_game.show_subscreen ( PBscreen_game.FORM_SUBS);
PBsubscreen_form.open_form ( new PBform_regular ( tmpstr ) );
}
catch (Exception e)
{
Gdx.app.error("PBLUAlibrary.open_form", e.getMessage());
}
return valueOf ( 0 );
}
}
It basically convert the lua parameter to string, create a new from and pass in parameter the string.
The declaration of the library functions goes like this:
public LuaValue call( LuaValue modname, LuaValue env )
{
LuaValue library = tableOf();
library.set( "open_form", new open_form() );
library.set( "open_system_form", new open_system_form() );
env.set( "pb", library );
return library;
}
Which could be the only "table" I can see in the whole system. This is generally used link the right class with the right function name.
Anybody have an idea?
most people say it is related to table and array indexing problems
It's related to table and array indexing. If you try to index an object and that object is nil, you'll get that error:
I am not using tables at all [..] Here is the lua script:
pb.open_form
pb is being indexed. It's probably nil.
I seems that I solved the problem by adding a require line to include the library. So the new script is:
String script = new String (
"require 'com.lariennalibrary.pixelboard.library.PBLUAlibrary'"
+ "function event_touch ( )"
+ " pb.open_form ('view_monster');"
+ " print ('I ran the next button lua script');"
+ "end");
It ask to include my library class which will add all the "pb.*" functions. I probably deleted the line by error, or managed to make it work somehow without it. Since this library will be required by all script, I might append it by default before each script I try to run.
Thanks Again

Tree Tagger for Java (tt4j)

I am creating a Twitter Sentiment Analysis tool in Java. I am using the Twitter4J API to search tweets via the hashtag feature in twitter and then provide sentiment analysis on these tweets. Through research, I have found that the best solution to doing this will be using a POS and TreeTagger for Java.
At the moment, I am using the examples provided to see how the code works, although I am encountering some problems.
This is the code
import org.annolab.tt4j.*;
import static java.util.Arrays.asList;
public class Example {
public static void main(String[] args) throws Exception {
// Point TT4J to the TreeTagger installation directory. The executable is expected
// in the "bin" subdirectory - in this example at "/opt/treetagger/bin/tree-tagger"
System.setProperty("treetagger.home", "/opt/treetagger");
TreeTaggerWrapper tt = new TreeTaggerWrapper<String>();
try {
tt.setModel("/opt/treetagger/models/english.par:iso8859-1");
tt.setHandler(new TokenHandler<String>() {
public void token(String token, String pos, String lemma) {
System.out.println(token + "\t" + pos + "\t" + lemma);
}
});
tt.process(asList(new String[] { "This", "is", "a", "test", "." }));
}
finally {
tt.destroy();
}
}
}
At the moment, when this is run, I receive an error which says
TreeTaggerWrapper cannot be resolved to a type
TokenHandler cannot be resolved to a type
I will be grateful for any help given
Thank you

Perl, Inline_Java, Java dynamic load of object and method

Can anyone assist me on how do I load the object FooBar dynamically and call the roquet function (dynamically) ?
I have this snippet in Perl:
#!/usr/bin/perl -w
use Inline Java => << 'End_Of_Java_Code';
class FooBar {
public FooBar(){}
public void roquet() {
System.out.println("HELLO!");
}
}
End_Of_Java_Code
use Data::Dumper;
use Class::Sniff;
my $sniff = Class::Sniff->new({class=>'FooBar'});
my $num_methods = $sniff->methods;
my $num_classes = $sniff->classes;
my #methods = $sniff->methods;
my #classes = $sniff->classes;
my #unreachable = $sniff->unreachable;
foreach my $method (#methods) {
if ( $method eq "roquet" ) {
print "$method\n";
}
}
I tried the following approaches and variations:
a. approach:
use Module::Load
my $package = "main::FooBar";
load $package;
$package->new();
$package->$rflmethod;//where rflmethod is the variable: $rflmethod='roquet';
b. approach:
no strict 'refs';
use Package::Stash;
my $stash = Package::Stash->new('main::FooBar');
my $coderef = $stash->get_symbol('&__new');
$coderef->()
This works:
my ($class, $method) = qw(FooBar roquet);
my $f = $class->new;
$f->$method;

Riak ReferenceError - with custom javascript

i am playing around a litle with riak an the riak-java-client.
Now i run into trouble with custom javascript, i want to use in a map reduce query.
If i use the pure javascript functions as anon functions, they work well.
So here is what i did:
uncommented in app.conf
{js_source_dir, "/tmp/js_source"},
then i stored mylib.js in /tmp/js_source
/* content of mylib.js */
var NS = (function() {
return {
mapHighValues: function(value, keydata, arg) {
var data = JSON.parse(value.values[0].data);
ejsLog('/tmp/map_reduce.log', JSON.stringify(data.High));
return [data.High];}
},
reduceSumHighValues: function(values) {
ejsLog('/tmp/map_reduce.log', "ReduceVals\n" + JSON.stringify(values));
return [values.reduce(function(prev, curr, index, array) {return prev + curr} ,0)];
}
}
})();
after that i restarted riak.
Here is the relevant java code:
MapReduceBuilder builder = new MapReduceBuilder(new RiakClient("localhost"))
.setBucket("goog")
.map(JavascriptFunction.named("NS.mapHighValues"), false)
.reduce(JavascriptFunction.named("NS.reduceSumHighValues"), true);
MapReduceResponseSource response = builder.submit();
Does anyone see my mistake?
Cheers
ApeHanger
Looks like an extra '}' after 'return [data.High];'

Categories

Resources