How to execute a matlab file on the background through Java? - java

I have a Java program that makes some changes to a matlab file that reads and executes a function. Is there a way to invoke and run this read.m file through the Java program without having to open Matlab? I tried searching matlabcontrol documentation but I didnt find anything relevant. I would appreciate it if anyone could guide me through.
Thank you in advance.
public static void tomatlab() throws MatlabConnectionException, MatlabInvocationException {
MatlabProxyFactoryOptions options =
new MatlabProxyFactoryOptions.Builder()
.setUsePreviouslyControlledSession(true)
.build();
MatlabProxyFactory factory = new MatlabProxyFactory(options);
MatlabProxy proxy = factory.getProxy();
proxy.eval("addpath('C:\\path_to_m_file)");
proxy.feval("read");
proxy.eval("rmpath('C:\\path_to_m_file')");
// close connection
proxy.disconnect();
}

You need a runtime environment vor M-code. Possibilities I see are:
use Matlab control which opens matlab
use builder ja which deploys a jar including the necessary parts of the runtime
if your M-code is compatible to octave, you can use the c++ interface of octave to create a dll, which can be used independent from Matlab .

Related

How do I make my Java CLI parsing library Jopt Simple parse an argument without any option?

So I'm building a Java CLI application that will have features similair to Windows's dir. I'm using the jopt-simple 4.9 library for my CLI parsing needs, and for acquiring options it seems pretty straightforward...
public static void main(String[] args) throws Exception {
OptionParser parser = new OptionParser("a::b?*");
OptionSet options = parser.parse(args);
parser.accepts("a", "Display all");
parser.accepts("b", "Bare output without metadata");
parser.accepts("?", "Displays this help prompt");
But what if I want to run my app without any args? Like I would run dir or ls to display local contents.
And what if I want to run my app without any options? Like if I'm just telling dir or ls which directory I want it to print out.
OK, so to achieve this is simply used the fact the JOpt also parses non-option arguments:
OptionParser parser = new OptionParser("a::b?*");
parser.allowsUnrecognizedOptions();
// In case the user specifies a path instead of just running the command
// locally, create an array out of the parsed directory strings.
String[] dirStringArray = options.nonOptionArguments().toArray(new String[options.nonOptionArguments().size()]);

How to save a Java object in Jython/Python

I'm building a Python UI using Tkinter. For the needs of the program, I've to connect Python with Java to do some stuff, so I'm using a simple Jython script as a linker. I cant use Tkinter with Jython because it's not supported.
Python (ui.py) -> Jython (linker.py) -> Java (compiled in jars)
To call the Jython function in Python I use subprocess as follows:
ui.py:
cmd = 'jython linker.py"'
my_env = os.environ
my_env["JYTHONPATH"] = tons_of_jars
subprocess.Popen(cmd, shell=True, env=my_env)
Then, in the Jython file, linker.py, I import the Java classes already added on the JYTHONPATH, and I create an object with the name m and call to some functions of the Java class.
linker.py:
import handler.handler
m = handler.handler(foo, moo, bar)
m.schedule(moo)
m.getFullCalendar()
m.printgantt()
The thing is that I've created a m object, that will be destroyed after the execution of jython linker.py ends.
So the question is: Is possible to save that m object somewhere so I can call it from ui.py whenever I want? If it's not possible, is there any other way to do this?
Thanks in advance.
I finally solved it by using ObjectOutputStream.
from java import io
def saveObject(x, fname="object.bin"):
outs = io.ObjectOutputStream(io.FileOutputStream(fname))
outs.writeObject(x)
outs.close()
def loadObject(fname="object.bin"):
ins = io.ObjectInputStream(io.FileInputStream(fname))
x=ins.readObject()
ins.close()
return x

how to open a file in a .jar through java

I want to open a file in .jar application and I want to use java to do this. Explaining, for example I have the file SF_Antivalent.xml and I want to open it with uppaal.jar. How do I do this using Java. I've written the following code, but it doesn't work.
public class test7 {
public static void main(String[] args){
Runtime rt=Runtime.getRuntime();
String file="C:\\Users\\V\\Documents\\diplwmatiki\\SFBs\\SF_Antivalent.xml";
Process p=rt("C:\\Windows\\System32\\java.exe", "-jar", "C:\\Users\\"
+ "V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar" + file);
}
}
and I get this error: the method rt(String, String, String) is undefined for the type test.
Is there something to do?
You question is a little confusing, however, I believe you want to run some application and pass the XML file as a parameter to it...
The problem is, you're treating rt as a function/method, not an object. Runtime has the an exec method used to execute external commands, for example...
Runtime rt=Runtime.getRuntime();
String file="C:\\Users\\V\\Documents\\diplwmatiki\\SFBs\\SF_Antivalent.xml";
Process p=rt.exec(new String[]{
"C:\\Windows\\System32\\java.exe",
"-jar",
"C:\\Users\\V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar",
file});
Also, each command or argument you want to send to this external process must be it's own element within the array you pass to this method
This means tha "V\\Documents\\uppaal-4.0.13-aca\\uppaal-4.0.13\\uppaal.jar" + file won't actually have the effect you think it will.
I'd also recommend that you use ProcessBuilder over Runtime#exec, but that's me.
The reason you are getting the error is because rt is a Runtime object, not a method. To call a method of rt do this:
rt.someMethodName();
With the code above you cannot get XML file, you're trying to execute something, instead of opening file inside JAR archive
Look into getResourceAsStream, this will give you possibility to load any file from JAR

Running a Java program from Adobe AIR's native process

I've use Adobe native process to run java program from my air app. Here the code and it works fine. But i should write absolute path to java runtime for that:
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java.
If user installed java runtime in diff folder, or have diff version then this code would not work. How i can detect where java were installed or maybe there is another right way to run java applications from air applications? If i run java library from terminal command line then i could just write "java -jar pdfbox-app-1.6.0.jar" etc. and it runs fine.
private function convertPdf2Txt():void{
var arg:Vector.<String> = new Vector.<String>;
arg.push("-jar");
arg.push(File.applicationDirectory.resolvePath("pdfbox-app-1.6.0.jar").nativePath);
arg.push("ExtractText");
arg.push("-force");
arg.push(File.applicationStorageDirectory.resolvePath("Data/1.pdf").nativePath);
arg.push(File.applicationStorageDirectory.resolvePath("Data/1.txt").nativePath);
var fjava:File = new File("/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java");
if (fjava.exists==false){
Alert.show("Can't find Java Runtime in default folder.","Idea Rover",mx.controls.Alert.OK, null,null,imgInfo);
return;
}
var npInfo:NativeProcessStartupInfo;
npInfo = new NativeProcessStartupInfo();
npInfo.executable = fjava;
npInfo.arguments = arg;
var nativeProcess:NativeProcess;
nativeProcess = new NativeProcess();
nativeProcess.addEventListener(NativeProcessExitEvent.EXIT,onNativeProcessExit);
nativeProcess.start(npInfo);
}
Absolute path is:
Mac OS: /usr/bin/java
Win OS: (default)
64bit : C:\Program Files\Java
32bit : C:\Program Files (x86)\Java
rather than popping up an Alert, you could open a file selection dialog, using File.browseForOpen(). then, the File you want is contained in the event passed by the Event.SELECT handler. this flow seems standard for applications i've used that need to access other applications, but aren't sure where to find their executables.
var npInfo:NativeProcessStartupInfo = new NativeProcessStartupInfo();
// setup npInfo, nativeProcess...
var fjava:File = new File("/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java");
if (!fjava.exists) {
fjava.addEventListener(Event.SELECT, onFileSelected);
fjava.browseForOpen("Where is Java located?");
}
private function onFileSelected (evt:Event) :void {
npInfo.executable = evt.target;
nativeProcess.start(npInfo);
fjava.removeEventListener(Event.SELECT, onFileSelected);
}
of course, you can use the same logic to find the file java needs to launch as well.
You may be able to determine where the Java binaries are by looking at the JAVA_HOME environment variable. I'd like to do the same thing as you're doing, so I'll post more after I do more research.

Running a program from within Java code

What is the simplest way to call a program from with a piece of Java code? (The program I want to run is aiSee and it can be run from command line or from Windows GUI; and I am on Vista but the code will also be run on Linux systems).
Take a look at Process and Runtime classes. Keep in mind that what you are trying to accomplish is probably not platform independent.
Here is a little piece of code that might be helpful:
public class YourClass
{
public static void main(String args[])
throws Exception
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("name_of_your_application.exe");
int exitVal = proc.exitValue();
System.out.println("Process exitValue: " + exitVal);
}
}
One question in S.O. discussing similiar issues. Another one. And another one.
You can get a runtime instance using Runtime.getRuntime() and call the runtime's exec method, with the command to execute the program as an argument.
For example:
Runtime runTime = Runtime.getRuntime ();
Process proc = rt.exec("iSee.exe");
You can also capture the output of the program by using getting the InputStream from the process.
The difficulty you will run into is how to get the application to know the path. You may want to use an xml or config file, but if you use this link, it should explain how to run a file:
http://www.javacoffeebreak.com/faq/faq0030.html
You may also want to consider passing in some kind of argument to your program to facilitate finding the specific program you want to run.
This could be with command line arguments, properties files or system properties.

Categories