Perl, Inline_Java, Java dynamic load of object and method - java

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;

Related

scala to java conversion for user-defined function (UDF) in sparksql

spark.sqlContext.udf.register('dataSource', (data: scala.collection.mutable.WrappedArray$ofRef, ofType : String) => {
var flag = ''
try{
val array: Seq[String] = data.flatten(x => Seq(x.toString()))
array.foreach(s => if(s.contains(ofType)) { flag = ofType })
}
catch {
println("Exception :" + x.getMessage)
flag = ''
}
flag;
})
It is not required to convert this Scala code into Java code. In Spark you can register a UDF in any of the languages and also make use of it in either Java or Scala as long as it is used in the same SparkSession or Context.

jni binding, javac error, unexpected token

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

When to use $em->getConnection()->close();, should I use it after every query

I am new to doctrine2(PHP) which is inspired from hibernate(java). I have searched at many places by didn't get appropriate answer.
what is the use of following code of line, what will happen if I do not use it?
$em->getConnection()->close();
For example If I have made following method in my class :
public static function deleteWish( $about_ilook_user_id, $link_ilook_user_id, $flush_automatic = TRUE )
{
$em = \Zend_Registry::get('em');
$new_link_wishes_objs = $em->getRepository( '\Entities\new_link_wishes' )->findBy( array( 'ilookUser' => $about_ilook_user_id, 'link_ilook_user_id' => $link_ilook_user_id ) );
foreach ( $new_link_wishes_objs as $new_link_wishes_obj )
{
$em -> remove($new_link_wishes_obj);
}
$em -> flush();
$em->getConnection()->close();
}
Should I call getConnection()->close(); on $em(entity manager).

CliBuilder argument without dash

Using Groovy CliBuilder, ideally I would like to have an cmd-line as follows:
./MyProgram.groovy CommandName -arg1 -arg2 -arg3
Is is possible to parse pull out the CommandName as an argument using CliBuilder?
You can do that if you set the property stopAtNonOption to false so that the parsing does not stop in CommandName. Then you can get the command from CliBuilder options. A tiny example below:
def test(args) {
def cli = new CliBuilder(usage: 'testOptions.groovy [command] -r -u', stopAtNonOption: false)
cli.with {
r longOpt: 'reverse', 'Reverse command'
u longOpt: 'upper', 'Uppercase command'
}
def options = cli.parse(args)
def otherArguments = options.arguments()
def command = otherArguments ? otherArguments[0] : 'defaultCommand'
def result = command
if (options.r) {
result = result.reverse()
}
if (options.u) {
result = result.toUpperCase()
}
result
}
assert 'myCommand' == test(['myCommand'])
assert 'MYCOMMAND' == test(['myCommand', '-u'])
assert 'dnammoCym' == test(['myCommand', '-r'])
assert 'DNAMMOCYM' == test(['myCommand', '-r', '-u'])
assert 'defaultCommand' == test([])

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