Java UI on top of Ruby script - java

I've been searching for answer without any luck for the below problem:
I have a quite lengthy ruby script which if you run in terminal(MAC) requires multiple inputs from user throughout execution. I would like to put on top of that script a Java UI - Swing or JavaFX so that the input is done via the Java UI throughout execution.
Is there any way to achieve this, how do you track the state of the script execution and how do you pass a input from Java UI to ruby script once required.
Now this is might be broad question so here is the example below how it would look like more or less:
I have a test.rb file with the below:
puts "enter your name:
#name = gets
puts #name
...
So Java would look something like:
String command = "ruby test.rb";
Process run = Runtime.getRuntime().exec(command);
run.waitFor();
...
So I could assign results of 'run' to the String but thats not much use.
I have looked at the JRuby but without any luck also (Maybe just dont understand it).
Many Thanks!

Related

Inheriting methods from an other program wrote in another language

I'm making a system for an app, witch have for objective to allow the user to create custom script to interact with the program by handleing events and reacting to them by calling functions. The main program is wrote in java, but If want to allow the script to be wrote in JavaScript. What is the best way to do that ?
I've tryed to use the sockets to transfer data and events, but I thinks it's a bit overkill, because the app and the scripts are on the same machine. Does it exist a better way to do that?
If I understand correctly, what you want to do is called Remote Procedure Call and it doesn't help much that all your code (java and js) runs on the same computer. But you can probably at least get away without authentication or security.
There are a bunch of libraries that may save you some trouble. You may want to take a look at those options:
https://en.wikipedia.org/wiki/Remote_procedure_call#General
I only got the occasion of using one: json-rpc, which isn't necessarily the best option, but it is the only one I can give you more details about.
The specification of the protocol is available here https://www.jsonrpc.org/specification and there should be Java and Javascript libraries to ease the implementation.
For example:
Java - https://github.com/briandilley/jsonrpc4j
Javascript - https://github.com/jershell/simple-jsonrpc-js
Calling this Java hello method:
public String hello(#JsonRpcParam(value="message") String message) {
return message;
}
From your client, a call to hello would look like this:
var jrpc = simple_jsonrpc.connect_xhr('localhost:8080');
jrpc.call('hello', {message: 'hello world!'}).then(res => console.log(res));
Of course there's additional configuration, at least on sever (java) side to make this work.

Is it possible to modify experiment parameter values after a model is run?

I'm following the Integrating AnyLogic Models with External Java Applications module and while I am able to change parameters before I run the exported java application, it seems the values become immutable once the model runs. Is there a way to dynamically modify parameter values at runtime?
Below is a snippet of my Java code:
final Simulation s = new Simulation();
IExperimentHost host = new ExperimentHost(s);
s.parameter1 = 50;
s.setup(host);
host.launch();
s.runTheModel();
s.parameter1 = 100;
The result is that parameter1 never changes from 50 to 100. Is there a way to circumvent this?
Try set_parameter. The help menu talks about this a little bit.
Edit:
Your original question was not directly linked to running as an external java application, but I think this could really simplify things. When you export your java application, look at the .bat file. You will see what the command line would look like to run the model. What we do when we are running from an external application is just have the external application call this command line, as opposed to what AnyLogic discusses in the help menu. A significant advantage of this is that you can easily mimic in the development environment what is going on in the exported model.
Ask your self why you are changing these parameters at runtime. Is it because of a read statement and you just don't have the data prior to the model run? If so, think about the order you instantiate your objects and don't start them until after you have the variables set that you want to use. This can be done by passing in parameters to main, setting database values, or having the main agent do various read statements.
Is it that you just want items to change over time? If so, consider variables, instead of parameters. Consider other objects that may allow you to more easily change flow. For example, does a valve before a pipeline or other sequence give you the level of control that you want?
At this point, would probably need more detailed information about what you are trying to accomplish / the system you are modeling, in order to provide any more specific advice.

Eclipse. Run two different mains when the second reads a static field of the previous

I have a Java project in eclipse which is divided in two parts; two different main classes that run two different Threads basically.
One contains loading, initialization and debug-showing procedures that are quite slow. While, the other manipulates the initialized data. In order to retrieve the information in the second part, the first one "saves" all the references inside a static map which contains instances of classes.
Does exist a way to run the first part only once, and then compile and run the second part more times? I tried with just set two different console and pressing the run button in different times but the static field of the first class looks not existing when the second runs.
I am working now only in the second part, so I need to test and start it many times. I really appreciate an help to save a lot of time wasted in always initialize the same thing.
ps : Everything works fine if I run both parts together.
thanks in advance
Luca
thanks to the replay (Multithreader, Stephen C) I am trying to make the question more clear and to ask how to solve it since my solution does not look the best one.....
EDIT 1 : The "first part" initializes the program and then runs an easy GUI which is periodically update. So as long as it shows up we shouldn’t care about how to manage input and output from the user
EDIT 2 : the "second part" reads information from the previous and send back strings to the GUI for debug purposes.
EDIT 3 : I do not have specific constrains in the shape of the project, so I can change the structure if there are better solutions. As well as for the way to run it.
FARTHER QUESTION 1 : there is a possibility to compile only one part of the project in eclipse while it runs all together? I mean, if two threads are running, can I stop one, re-compile it and run it again in a way that it can see the instances created from the first thread which never stops? Basically I need to refer at the same static variable loaded in memory, if it exists.
FARTHER QUESTION 2 : or more luckily does exist a way to store and load in a file instances of Java classes avoiding to write from sketch a mapping mechanism from/into txt files?
It is not entirely clear what you are asking here, but I'm assuming that you are talking about running the "first part" and the "second part" in the same JVM ...
Yes, it is possible. But it is not straightforward.
Basically, you need to refactor your code so that there is some kind of "control box" that the user can interact with from the outside. For instance, this might just be a simple command loop that reads commands from standard input and runs them. (Alternatively you could turn your application into a "service" that accepts requests over a network socket, via RMI, via HTTP, etcetera.)
Then you wire things up so that there is a "command" to run the "second part" of your application in response to the user's request.
That's the basics. The other thing you want to do is to "compile and run the second part [many] times". That implies that you need to set up your "control box" so that it can load a fresh copy of the code for the "second part" after you have modified and recompiled it. To achieve this, you will need to create a new ClassLoader object (each time) and use that to load the classes that make up the "second part". This is possible, but a bit tricky. The problems you are going to need to address include:
Splitting the "first part" and the "second part" into separate JAR files (or directory trees). The "first part" needs to be self-contained ... no dependencies on classes in the "second part".
Make sure that there are no runtime references from the "first part" data structures to instances of objects / enums in the "second part".
If you don't get the above right, you are likely to experience "permgen" storage leaks and mysterious type cast errors.
All in all, there's a lot that needs to be done to make this work. Unless you already understand all of the technologies involved, I'm doubtful that it will save you time overall. A better idea might be to figure out how to speed up the initialization of the "first part"; e.g. by doing lazy initialization, or caching the data structures using some fast / light-weight persistence mechanism.
I think it is better to change your design unless there is a requirement for it to stay the same.
Although I do not have the requirements or what you are actually trying to accomplish, I suggest you the following design:
1. App_1 does the calculations and then writes the results into file
2. App_2 reads checks for the file, if NOT exists display error message; otherwise read the file and keep going...
I guess I found a tricky solution. It is dirty but it works natively in the eclipse debugger.
I am running in debugging mode a main method which create a thread that works as a caller. This runs the first part of the project and wait until the initialization is complete (note that the first part doesn't end here, it remains looping to show debugging information based on a static class which evolves with the second part of the program). Then it starts with an infinite loop where it just calls the second part that I want to test and change: here there are also a breakpoint.
Well, now I can coding in the second parts while the eclipse debugger is waiting in the breakpoint than save it and hit F8. The debugger resumes, the algorithms runs and then it stops again in the breakpoint. Just check if works, eventually change something then save and hit F8 again without wait to re-initialize the first part of the project.
Probably this method has to be restarted after a while but still, it better then restart every time :)
many thanks to all your help.
If somebody has more elegant way to do that they are welcome!!

rJava startMainLoop() function kills Java operations

I've developed an interface that allows a user to load and manipulate data. The GUI is developed in Java and all the computational stuff is done in the background by R, linking the two with jri. The idea is that the user doesn't have to have any knowledge of R to use it, it's all options and buttons. However, i'd like to give the user the option to write some code if necessary. So here is my problem:
If I use the following code to start the Rengine and not let the user interact via console, everything works fine:
Rengine re=new Rengine(null, false, new TextConsole());
But if I use this:
Rengine re=new Rengine(null, true, new TextConsole());
The functionality of the gui doesnt work. I tried using the
re.startMainLoop();
function after the data was loaded. I was able to manipulate the data from the comand line in R, for example I could make a new variable from a column of the data loaded:
newVariable<-data$column1
But yet again, I couldn't use the gui anymore. Has anyone got any ideas or explainations as to why this is?
Thanks in advance,
Aran
Fundamentally, if REPL is not running, R is simply used via eval calls from your code. You have control at all times, except during the actual evaluation. That is the most common use, because you can do pretty much anything that way.
The moment you enable the event loop (REPL), you have to implement the callback methods that are used by the loop. By design R surrenders the control only by calling the rReadConsole callback which you have to implement. The example TextConsole works only as a demo, it uses blocking call (readLine()) to wait so you definitely don't want to use that in your GUI. You'll have to implement all callbacks correspondingly to react to your GUI's elements (wait in ReadConsole for your GUI to wake it up from a separate thread, dispatch WriteConsole to your elements etc.). You can have a look at JGR how it's done properly. Unless you are really building a general purpose R GUI, I wouldn't go into that trouble ...
(PS: please use stats-rosuda-devel mailing list for rJava/JRI questions - you get answers much faster)

How do I test a concurrent Java program which expects cmd line arguments?

I have a Java program which its main method (in the main class) expects command line arguments. The program is also concurrent (uses threads and stuff).
I want to do massive refactoring to the program. Before I start refactoring I would like to create a test suit for the main method. I would like to test the main method with different cmd line arguments. I'll want to run these tests automatically after each refactoring step I make. How do I create a test which passes cmd line arguments?
I cannot use JUnit because as far as I know it doesn't work well with concurrent programs. I'm also not sure if you can pass cmd line arguments with JUnit.
I'm using eclipse.
Take a look at multithreadedtc. http://code.google.com/p/multithreadedtc/
Consider using JMeter. With JUnit sampler you can make concurrent JUnit tests easily, and see the result. See this question for more details.
I'm not familiar with the various automation tools available specifically for multi-threading, so I won't comment on them. But on simple yet effective option is to log key events from the running program to a CSV file. You could log the final result (if it is a calculation type program) or log out at every instance in the program where some key state is changed or event occurs. Because it's a multi-threaded app you would have to pay attention to comparing the sequence of logged data, if you can not guarantee the relative ordering of the key events you expect to see then compare output using key-value type results. Either way, the idea would be to create test data files which you can use for automated comparison when back testing.
Awaitility can also be useful to help you write deterministic unit tests. It allows you to wait until some state somewhere in your system is updated. For example:
await().untilCall( to(myService).myMethod(), greaterThan(3) );
or
await().atMost(5,SECONDS).until(fieldIn(myObject).ofType(int.class), equalTo(1));
It also has Scala and Groovy support.
await until { something() > 4 } // Scala example

Categories