LuaJ hyperbolic library example using set() instead of require() - java

I'm using the example listed here:
http://www.luaj.org/luaj/3.0/README.html#5
It works fine, but instead of using inside the Lua script:
require 'hyperbolic'
I would like to use this or something similar in the java code
_G.set("hyperbolic", new hyperbolic());
Mostly to pass initial arguments to hyperbolic (like new hyperbolic(2.4, 1.67) when initializing it, so the Lua script is simple and "kid" friendly.
Any ideas or suggestions? Google isn't helping, possibly because I'm searching for the wrong thing..

By convention, instances of Java classes that implement lua libraries need to be called once with arguments (modulename, environment), and they set up the library for the supplied environment.
As coded, the hyperbolic library ignores the module name, and puts its functions in globals.hyperbolic
Globals globals = JsePlatform.standardGlobals();
hyperbolic module = new hyperbolic();
module.call(LuaValue.valueOf("hyperbolic"), globals);
This loads the library so you can use the function from scripts that have those globals as their environment. For example,
LuaValue chunk = globals.load(
"print( 'sinh(0.5)', hyperbolic.sinh(0.5) )");
chunk.call();
will then output
sinh(0.5) 0.5210953
Unlike require(), this example does not populate the package.loaded table, so if you go on to require('hyperbolic'), it may be loaded a second time.

Related

Dynamically build java/scala method body at runtime and execute it

Suppose I have the following Interface in java:
public interface DynamicMethod {
String doit();
}
I would like to build an Object during runtime which conforms to the above interface such that I inject doit method body in it and then execute it? Is this possible with Java Reflection API, or any other way? Or probably in some way in Scala?
Note that doit body for my objects would be dynamic and are not known a priori. You can assume that in run-time an array CodeArray[1..10] of Strings is provided and each entry of this array holds the code for each doit method. I would appreciate if you could answer with a sample code.
The context:
I try to explain the context of the problem; nonetheless, the above question still remains independent from the context.
I have some commands say C1,C2, ...; each command has certain parameters. Based on a command and its parameters the system needs to perform a certain task (which is expressible using a java code.) I need that these commands are stored for future execution based on user demand (so the CodeArray[1..10] in the above holds this list of java codes). For example, a user chooses a command from the list (i.e., from the array) and demands its execution.
My thought is that I build an engine that based on the user selection, loads the corresponding command code from the array and executes it.
With your context that you added, it sounds to me like you have an Interpreter..
For example, SQL takes input like "SELECT * FROM users", parses and builds a tree of tokens that it then interprets.
Another example: Java's regex is an interpreter. A string like "[abc]+" is compiled into tokens, and then interpreted when executed. You can see the tokens (called Nodes) it uses in the source code.
I'll try to post a simple example later, but the Interpreter Pattern doesn't use dynamically generated code. All of the tokens are concrete classes. You do have to define all possible (valid) user input so that you can make a token to execute it however. SQL and regex has a defined syntax, you will need one also.
I think Byte Buddy would be helpful in your case. It's an open source project maintained by a very well respected Java developer.
Take a look at the Learn section, they have a very detailed example there:
http://bytebuddy.net/#/tutorial
Currently it's not very clear what's your aim. There are many approaches to do this depending on your requirements.
In some cases it would be enough to create a Proxy and an InvocationHandler. Sometimes it's reasonable to generate Java source, then invoke JavaCompiler in runtime and load the generated class using URLClassLoader (probably that's your case if you're speaking about strings of code). Sometimes it's better to directly create a bytecode using libraries like ASM, cglib or BCEL.

Changing the behaviour of a Java app dynamically using Groovy

I am investigating methods of dynamically modifying the behaviour of a Java application (specifically, I'm trying to make a Minecraft mod that allows users to modify the behaviour of the objects they find by writing code without the need to restart the game) and I stumbled upon Groovy. My question is: is it possible to integrate Java and Groovy in such way they "share" objects? (I'm thinking about having a specific set of classes that are actually Groovy code so you can change the code during runtime, similarly to what you can do in any Smalltalk implementation)
Take a look at Integrating Groovy in a Java Application. It shows examples of how you can run a Groovy script from inside a Java application and share data between them using groovy.lang.Binding.
What a cool idea!
1. Groovy: Java and Groovy can share objects and call back and forth. Groovy classes that implement Java interfaces are easily called from Java. (There are other ways, like calling groovyObject.invokeMethod("methodName", args) from Java.) Of JVM languages, Groovy has the tightest integration with Java. It's also easy for Java programmers to learn since it shares so much with Java.
The book Groovy in Action has a chapter on "Integrating Groovy" that explains and compares the approaches (in more detail than the reference docs do): GroovyShell, GroovyScriptEngine, GroovyClassLoader, Spring integration, and JSR-223 ScriptEngineManager. GroovyClassLoader is the most capable choice.
However, while it's easy to compile and load Groovy code at runtime, I'm puzzled about how to change behavior of existing object instances (short of the notes below on hot swapping). (It might depend on whether the class overrides a Java interface or subclasses a Java class.) Consider:
class G implements Runnable {
void run() { println 'Groovy' }
}
g = new G()
g.run()
This prints Groovy. Now redefine the class:
class G implements Runnable {
void run() { println 'Groovy!' }
}
g1 = new G()
g.run()
g1.run()
This prints
Groovy
Groovy!
Now use the meta-class to change methods at runtime:
G.metaClass.run = { println 'Groovy!!!' }
g2 = new G()
g.run()
g1.run()
g2.run()
This prints
Groovy
Groovy!
Groovy!
If we omitted implements Runnable from those class definitions, then the last step would instead print
Groovy
Groovy!
Groovy!!!
But with our class that does implement Runnable, now do:
G.metaClass.run = { println 'Very Groovy!!!' }
g3 = new G()
g.run()
g1.run()
g2.run()
g3.run()
this prints:
Groovy
Groovy!
Very Groovy!!!
Very Groovy!!!
A workaround would implement the methods in closures held in class variables.
2. Hot Swapping: If the main point is to redefine method bodies at run time for classes with existing instances, then you can simply run within an IDE's debugger and use hot swapping.
E.g. for IntelliJ, here are the instructions to configure hot swapping of Java and Groovy code.
3. Expanded Hot Swapping: If you also want to be able to add/remove methods and instance variables at run time, then see this JetBrains article on extended hot swapping via DCEVM (Dynamic Code Evolution VM).
See Hot Swap code code at https://github.com/HotswapProjects
Also see this SO Q&A on hot swapping techniques.
I'm not sure that's something you can accomplish with Groovy without compiling it. You could do it, but the "scripting" aspect of Groovy won't help you. I'd look into having the player write javascript and using Java's ScriptEngine. See here: http://docs.oracle.com/javase/7/docs/technotes/guides/scripting/programmer_guide/
Yes, You can achieve that. For example, You have something written in java that uses some objects from let's say spring context. So now what u can do is :
execute groovy script before that java code is executed,
use delegate design pattern to wrap it, overwrite some methods
finaly put it back into context.
So basicly in moment where Your java code is executed, he'll get a wrapped object with some changes made in runtime.
If that's what are You trying to do, let me know i could write You some example code.

Java to JavaScript using GWT compiler

I have some Java code written that I'd like to convert to JavaScript.
I wonder if it is possible to use the GWT compiler to compile the mentioned Java code into JavaScript code preserving all the names of the methods, variables and parameters.
I tried to compile it with code optimizations turned off using -draftCompile but the method names are mangled.
If GWT compiler can't do this, can some other tool?
Update
The Java code would have dependencies only to GWT emulated classes so the GWT compiler would definitely be able to process it.
Update 2
This Java method :
public String method()
got translated to this JavaScript funciton :
function com_client_T_$method__Lcom_client_T_2Ljava_lang_String_2()
using the compiler options :
-style DETAILED
-optimize 0
-draftCompile
So names can't be preserved. But is there a way to control how they are changed?
Clarification
Say, for example, you have a sort algorithm written in Java (or some other simple Maths utility). The method sort() takes an array of integers. and returns these integers in an array sorted. Say now, I have both Java and JavaScript applications. I want to write this method once, in Java, run it through the GWT compiler and either keep the method name the same, or have it change in a predictable way, so I can detect it and know how to change it back to sort(). I can then put that code in my JavaScript application and use it. I can also automatically re-generate it if the Java version changes. I have a very good reason technically for this, I understand the concepts of GWT at a high level, I'm just looking for an answer to this point only.
Conclusion
The answer to the main question is NO.
While method name can be somewhat preserved, its body is not usable. Method calls inside it are scattered throughout the generated file and as such, they can't be used in a JavaScript library which was the whole point of this topic.
Although you can set the compiler to output 'pretty' code, I suggest you write export functions for the classes you want to call from outside your GWT project. I believe somewhere in the GWT documentation it's detailed how to do this, but I couldn't find it so here an example I just created.
class YourClass {
public YourClass() {
...
}
public void yourMethod() {
...
}
public static YourClass create() {
return new YourClass();
}
public final static native void export() /*-{
$wnd.YourClass = function() {
this.instance = new #your.package.name.YourClass::create()()
}
var _ = $wnd.YourClass.prototype;
_.yourMethod = function() {this.instance.#your.package.name.YourClass::yourMethod()()}
}-*/;
}
EDIT
To elaborate, your code will get obfuscated like normal, but thanks to the export function, you can easily reference those functions externally. You don't have to rewrite anything from your Java class in JavaScript. You only write the references in JavaScript, so you can do this:
var myInstance = new YourClass();
myInstance.yourMethod();
Of course you have to call the static export method from somewhere in your GWT app (most likely in your EntryPoint) to make this work.
More info about referencing Java methods from JavaScript:
http://code.google.com/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html#methods-fields
No - this isn't possible with the GWT compiler, since the GWT compiler is build to generate optimized and very performant JavaScript out of Java.
The big advantage is, that you can maintain your projekt in Java and compile it with GWT to JavaScript. So there is no need to prevent the variable-names and method-names in the JavaScript result, since all changes and work is done in the JAVA-sources.
Working in the JavaScript-output of GWT just isn't that easy and is really a lot of work!
Update:
By a hint of David, I found the Compiler-Option "-style". You can have a try with the following options:
-style=PRETTY -optimize=0
I have no idea if this will really generate "human readable" code. I think it won't, since the GWT framework will still be part of the resulting JavaScript and so it will be difficult to make changes to the JavaScript-result. Have a try and let us know ...
Maybe I can answer your second question: "If GWT compiler can't do this, can some other tool?"
I am using Java2Script for quite a while now, also on quite large projects. Integration with native JavaScript is fine, names are preserved, and after some time one can even match the generated JavaScript (in the browser debugger) with the original Java code with little effort.
Udo
You can "export" your function by writing inline JavaScript that calls it, and there is a tool gwt-exporter that does this automatically when you annotate classes and methods with #Export and similar. More information: https://code.google.com/p/gwtchismes/wiki/Tutorial_ExportingGwtLibrariesToJavascript_en

Dynamically editing/creating classes in Java Android

I am looking for a way to dynamically define classes and instantiate them in Android, at runtime. From my understanding, this is already done in Android, I just need some help figuring it out.
I can a similiar result in Javascript and PHP. I know it can be done in Java using something like ASM, BCEL or CGlib. However, I do not know enough about any of these to understand if they will work on Android. Or, of they will work, what are the implications?
If, hypothetically, all three will work in Android, can someone point me in the correct direction as to where to start understanding which to use, and how to use it?
I haven't done much Java programming, and I have only just recently been working with it in Android, so, I appreciate all of the help/correction I can get. With that said, I would appreciate if your answer is NOT simply: Don't do this. I am looking for how to do this specifically, not how to do it right. At least, not until my app comes crashing down. :)
I believe that this already happens in Android in the following situations: (Not 100% SURE)
Creating an object from JSON.
AIDL
Don't do this :)
I actually doubt there are JSON libraries that behave this way; the two accepted ways I know (I am not an expert on this, though) are either to create some sort of data structure holding name-value pairs - i.e. add stuff to a data structure but not create a new class - or prepare a template of a class which will be populated from a JSON object.
Java, being statically-typed, is not really suitable for creating whole new classes at run-time, and there is no reflection support for that - though there is support for accessing objects of unknown types (e.g. querying for all their fields / methods).
What you can do is to manually write a java class to a file - either in Java code and then compile it somehow, or directly in bytecode - and then load that file at runtime. It's ugly, but it will work. Then it's just the same as any runtime loading of classes - either you rely on the base class / interface of the loaded class, or you have to use reflection to do anything meaningful with it.
For those who really do want to do this (for instance using Dalvik's JIT to create a fast interpreter for another language), there is this project:
http://code.google.com/p/dexmaker/
Which allows you to programatically create classes, variables and methods.
Generating Dalvik Bytecode at Runtime on-device Using ASM or BCEL
This example use ASM and BCEL to generete two classes on-device.
The classes are created into SD Card memory and then they are loaded into Android operating system dynamically.
The following class is the template of the example:
public class HelloWorld {
public static void hello(){
int a=0xabcd;
int b=0xaaaa;
int c=a-b;
String s=Integer.toHexString(c);
System.out.println(s);
}
}
Firstly I have used BCEL or ASM to create a new ad-hoc class in SD Card.
Secondly I have converted the Java Class to a Dex Class with the Dxclient utiliy in SD Card.
Finally I have created a jar file and then I have loaded this package into the device from SD Card
DXClient reference
https://github.com/headius/dexclient/blob/master/src/DexClient.java

Call javascript function from Java (Groovy) class

I have a javascript function (very big one!) that I need its functionality in a Java (Groovy) class. It is a simple calendar converter. I can rewrite it in groovy but just want to know if it is possible to call javascript function from a java (groovy) method? I guess functional testing libraries like selenium and Canoo should have something like this, am I right?
PS: I don't want to wake up a real-world browser in order to use its JS runtime env.
Thanks,
As mentioned in the other answers, it is possible to use the Scripting API provided as part of the javax.script package, available from Java 6.
The following is a Groovy example which executes a little bit of Javascript:
import javax.script.*
manager = new ScriptEngineManager()
engine = manager.getEngineByName("JavaScript")
javascriptString = """
obj = {"value" : 42}
print(obj["value"])
"""
engine.eval(javascriptString) // prints 42
It is not necessary to call a browser to execute Javascript when using the Scripting API, but one should keep in mind that browser-specific features (probably the DOM-related functionalities) will not be available.
You can use Rhino, an implementation of JavaScript language in Java. Here is example of calling JavaScript function from java, but you can do it from groovy also.

Categories

Resources