Good day all,
I am trying to figure out how to allow users to call a method on some specified data.
I would like to provide a predefined set of functions:
Moving average, moving_ave(x,5) ..would be a 5 day moving average on x.
3*x+y....and so on...
So basically, i will provide the users with various data series (x,y,z....) and a set of functions moving_ave, + - / * ....and they should be able to write simple formulas (restricted to the functions i provide).
how can this be done?
I will be deploying this on App Engine for Java.
so for i have found out about JSR-223...but i'm not sure if its appropriate? I am thinking i can use the Eval function.
Thanks,
It sounds like what you want is an interpreter for a simple grammar. Be very wary of approaches such as that suggested by Aerosteak; allowing your user to call functions in your code directly is dangerous, and it's easy to make mistakes sandboxing it, resulting in security vulnerabilities. It'll also require you to write your own parser.
The easiest approach is probably to use an existing language - Javascript probably fits very well, and you can use Rhino, a Javascript interpreter written in Java.
You will need to use Reflection to call unknow Method. Look a Apache BeanUtil.
You can have a TextBox with the value: 1,2,3, Convert these values to Object Array.
Have another ComBo Box with all you possible Method you can call.
Then use Bean Util to call the method with the Object Array.
For Exemple:
class MyMathManager{
public void doCalculationType1(Object args...){..}
public void doCalculationType2(Object args...){..}
public void doCalculationType3(Object args...){..}
Then Look at the Java of BeanUtil to call these Method.
Good Luck.
This sounds like something that could probably be done on the client, rather than the server. You could write a few handy javascript functions that call a restful API on the server to provide the needed data to a few more handy javascript functions that do the useful calculations. It's almost always safe to allow users to eval on their own clients.. they can do it in any case.
Related
dear stackoverflow community.
Currently, I am working on a project. This project shall have a server and clients connecting to it. Because of their simplicity, I'd like to use Java's integrated ServerSockets and Sockets.
In my project, data shall be sent from the client to the server and opposite.
My initial idea is to just send JSON and then parse it as receiver and get the data from that.
I'm a little unsure about that though, since JSON isn't something that's integrated into Java, but comes from Java script. Also, I'm currently using a Multithreaded-Socket-Server, so I have a ClientHandler Thread class. In that class, the messages were received, parsed and the "action" parameter was read out of the JSON and then I did a switch statement with multiple actions and their functions. I don't think that's a good way of doing that either.
So, my question is:
How can I do that better, and maybe do I have to use something else?
Thanks in advance.
It is true that JSON grew out of JavaScript, but it is a reasonable definition language on its own and I don't see any reason you shouldn't use it. There are libraries for parsing it so you don't have to.
Assuming your JSON structures are different for different purposes, and complex enough to need different classes to represent them, I like the idea of the JSON having a parameter that identifies the class to which it belongs, after which you can hand off parsing to a class that understands the designated output. Then a class can read the JSON, get the type, and some the specific parsing routine can go from there to an object created for the purpose.
I don't see anything wrong with an action string, either; it's served well enough for Swing and some other UIs, after all. Instead of branching out to a function, depending on complexity again, you could have action classes that all implemented an interface, and the action 'verb' could tell you which one (out of a map, say?) to get and execute the 'performAction()' method on or whatever you want to call it.
I don't know how clear this is from a quick description; would be willing to chat about it in an SO chat room if you care about it.
I'm working on building a custom Simulink block as a Matlab Toolbox. In order to avoid matlab's language to program the system, I'd like to make the system in Java as much as possible. I've researched the Matlab <-> Java interface, and it seems possible to do this. However, the one thing I couldn't find any information about was storing my custom Java object (holding the block's data) inside the Simulink block.
I conducted a quick test, and it seems storing a Java.lang.String instance is possible. However, that was a relatively simple test. Before jumping in head first, I wanted to check if this was even possible. Does anyone have experience with a similar setup? Does the object simply need to be Serializable to work?
For background information, I'm looking to implement the non-math part (GUI code, processing, etc) in Java. Math related elements would likely remain in matlab.
To store your Java object inside the block you should use its UserData block parameter. According to the documentation, you can put any data type in this parameter.
The only problems I can see with this are saving/loading and creation of new blocks. Saving/loading should be solved using serialization, but you will have to try it to see. If this doesn't work, then you could create a hidden mask parameter for your blocks, serialize your Java object to a string, and save the data in this mask during the PreSaveFcn callback. The data could be deserialized from the mask parameter in the LoadFcn callback.
For the creation of new blocks, you should set the PreCopyFcn callback of your library block and create your new Java object there. I have the feeling that if you don't do this, then MATLAB will copy the reference to your object from UserData (if one exists there already), which is probably not what you want.
You probably also want to override the OpenFcn callback since your aim is to use your Java object as a kind of souped-up mask, so that when a user double-clicks on the block you can show your custom UI.
For more information on block callback parameters, see this.
I'm working on a Scala-based script language (internal DSL) that allows users to define multiple data transformations functions in a Scala script file. Since the application of these functions could take several hours I would like to cache the results in a database.
Users are allowed to change the definition of the transformation functions and also to add new functions. However, then the user restarts the application with a slightly modified script I would like to execute only those functions that have been changed or added. The question is how to detect those changes? For simplicity let us assume that the user can only adapt the script file so that any reference to something not defined in this script can be assumed to be unchanged.
In this case what's the best practice for detecting changes to such user-defined functions?
Until now I though about:
parsing the script file and calculating fingerprints based on the source code of the function definitions
getting the bytecode of each function at runtime and building fingerprints based on this data
applying the functions to some test data and calculating fingerprints on the results
However, all three approaches have their pitfalls.
Writing a parser for Scala to extract the function definitions could be quite some work, especially if you want to detect changes that indirectly affect the behaviour of your functions (e.g. if your function calls another (changed) function defined in the script).
The bytecode analysis could be another option, but I never worked with those libraries. Thus I have no idea if they can solve my problem and how they deal with Java's dynamic binding.
The approach with example data is definitely the simplest one, but has the drawback that different user-defined functions could be accidentally mapped to the same fingerprint if they return the same results for my test data.
Does someone has experience with one of these "solutions" or can suggest me a better one?
The second option doesn't look difficult. For example, with Javassist library obtaining bytecode of a method is as simple as
CtClass c = ClassPool.getDefault().get(className);
for (CtMethod m: c.getDeclaredMethod()) {
CodeAttribute ca = m.getMethodInfo().getCodeAttribute();
if (ca != null) { // i.e. if the method is not native
byte[] byteCode = ca.getCode();
...
}
}
So, as long as you assume that results of your methods depend on the code of that methods only, it's pretty straighforward.
UPDATE:
On the other hand, since your methods are written in Scala, they probably contain some closures, so that parts of their code reside in anonymous classes, and you may need to trace usage of these classes somehow.
Is there any way to know how many times a instance of a class has invoked its member method.
I think(not sure), one way is to have a dedicated a member variable for a method, But that will not be feasible if we have so many methods.
For example:
class A{
public void someMethod(){
}
}
and i have a instance say
A a = new A();
So I want to know the Number of times a has invoked someMethod in a program.
We can have any number of methods.
If you need this information inside the program, this is exactly what aspect oriented programming is meant for. Using AspectJ, it would be quite easy. Spring AOP will probably also work.
Indeed, AOP would be the right tool here and I would write a little aspect to use JAMon (which can precisely gather statistics such as hits, time statistics (avg,total,min,max), concurrency statistics and more). See this previous answer for an example (or goolge a bit). If you are using Spring, then Spring has a ready to use JamonPerformanceMonitorInterceptor.
There are a few approaches you could take, depending on how easily you can modify the code:
just add the counter variable as you suggest; clumsy if you have to add it in a lot of places, but easy to code
put your counter code in some other utility class, with a single method that you call from all relevant places to "increment counter for this method"; the utility method in question then examines the call stack-- e.g. via (new Exception()).getStackTrace()-- to see who was calling and increment the relevant counter
use a profiler that provides this facility
use the ASM library to add a counter.
use the Java instrumentation framework to modify the class definitions of relevant methods on the fly as the classes are loaded; this is potentially the most flexible-- you can even instrument code that you haven't actually written yourself and can't modify, and it means you don't have to alter the code of the actual classes you want to perform counting on-- but it is by far the most complex to code.
You may consider using profilers, e.g. one from NetBeans or YourKit, etc.
There a lot of Open Source Java Profilers.
A profiler does dynamic program analysis (as opposed to static code analysis), and shows a program's behavior, gathering information as the program executes. Some of these profilers shows method invocation statistics.
If you have access to JProbe it will tell you the number of times a method was invoked by a particular instance.
They say MAT is also good and its free, I haven't tried it yet.
It's possible to do with java.lang.reflect.Proxy class. In Horstmann's book 'Core Java. Volume I' this technique is described in details.
I've been playing with DWR and converters for a while and I really wanted to map my Java classes to JavaScript classes. Using DWR converters, I have the option to point out what is the name of my JS constructor given a Java class. So far so good... The problem arises when my JS constructor is within a JS package-like name (just like YUI's package system, eg my.beautiful.package.MyClass). DWR's current implementation doesn't allow me to use this kind of construct, giving me a SyntaxError when I try to use it. Is there an elegant way arround this limitation?
As far as I know the this isn't possible directly. I have in my current work project experimented with enhancing each returned object on the client side with methods from a Javascript class, which gets the result that I think you are interested in.
DwrService.getThings({
callback:function(things){
for(thing in things){
YAHOO.augmentProto(thing, my.beautiful.package.MyClass);
}
// do your stuff here
}
});
I'll have to check at work on monday (now is sunday) that augmentProto is correct one to use, but I think it is. There may even be a better hook into DWR that'll allow you to do this on the fly automagically.