Running R from terminal via Java - java

I'm trying to run R using Java. I have R installed on my Mac and I've used it plenty of times from the terminal.
In the terminal, to start R, one simply types "R"
Ex:
Macintosh-11:Desktop myname$ R
R version 2.12.2 (2011-02-25)
Copyright (C) 2011 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
>
So, what I would like to do is run R through Java, via the terminal. So, I wrote myself a Java class:
public class javar {
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec("R");
}
}
However, when I compile and then execute, using
java javar
I don't see R start. I simply see the program finish executing, and then the terminal is ready for another command.
How can I achieve what I'm trying to do?

when I encountered your problem, I ended up using JRI, which not only creates an R/Java connection, but allows you to exchange matrices and vectors to/from the two.
Although I don't suggest it, your approach may work, but R will not "hang" after you launch it, it will just execute nothing and exit. Try adding the "--vanilla" option and obviously feed some code to it, with --file=yourScript.R and eventually arguments using --args
public class javar {
public static void main(String[] args) throws Exception {
Runtime.getRuntime().exec("R --vanilla --file=yourScript.R");
}
}

Related

Is there a way to run Java in R?

I am working on a project which is primarily in R and requires Java to run. So, I need a way to run Java in R itself.
For example, is there any way to run this code in R?
public static void main(String[] args){
for(int i=0;i<5;i++){
System.out.println("HelloWorld");
}
}
** Lib in R (v8,rJava,rserve)
Actually, the first google result for "javascript in r" that I got leads to vignette of js package, that uses V8 package providing V8 implementation of JavaScript for R. You can use either of the packages to run JS code from R.

Java check if program is installed on windows

Is there a way to check if a specific program is installed on Windows using Java?
I'm trying to develop a Java program that automatically creates zip archives by using the code line command from 7-Zip.
So, I would like to check in Java if on my windows OS '7-Zip' is already installed. No check for running apps or if OS is Windows or Linux. I want to get a bool (true/false) if '7-Zip' is installed on Windows.
The library Apache Commons has a class called SystemUtils - full documentation is available at https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils.html.
In this library you have the following static boolean properties at your disposal:
SystemUtils.IS_OS_LINUX
SystemUtils.IS_OS_WINDOWS
The unix-like solution would be to simply try to run the program with --version flag (on windows probably the /? or - like in the 7zip case - without any at all) and check whether it fails, or what the return code will be.
Something like:
public boolean is7zipInstalled() {
try {
Process process = Runtime.getRuntime().exec("7zip.exe");
int code = process.waitFor();
return code == 0;
} catch (Exception e) {
return false;
}
}
I assume that you're talking about Windows. As Java is intended to be a platform-independent language and the way how to determine it differs per platform, there's no standard Java API to check that. You can however do it with help of JNI calls on a DLL which crawls the Windows registry. You can then just check if the registry key associated with the software is present in the registry. There's a 3rd party Java API with which you can crawl the Windows registry: jRegistryKey.
Here's an SSCCE with help of jRegistryKey:
package com.stackoverflow.q2439984;
import java.io.File;
import java.util.Iterator;
import ca.beq.util.win32.registry.RegistryKey;
import ca.beq.util.win32.registry.RootKey;
public class Test {
public static void main(String... args) throws Exception {
RegistryKey.initialize(Test.class.getResource("jRegistryKey.dll").getFile());
RegistryKey key = new RegistryKey(RootKey.HKLM, "Software\\Mozilla");
for (Iterator<RegistryKey> subkeys = key.subkeys(); subkeys.hasNext();) {
RegistryKey subkey = subkeys.next();
System.out.println(subkey.getName()); // You need to check here if there's anything which matches "Mozilla FireFox".
}
}
}
If you however intend to have a platformindependent application, then you'll also have to take into account the Linux/UNIX/Mac/Solaris/etc. (in other words: anywhere where Java is able to run) ways to detect whether FF is installed. Else you'll have to distribute it as a Windows-only application and do a System#exit() along with a warning whenever System.getProperty("os.name") is not Windows.
Sorry, I don't know how to detect in other platforms whether FF is installed or not, so don't expect an answer from me for that ;)

Running an R script from Java

I've got a problem when I try to run a R script from Java Netbeans on Mac OS. I truly look for an answer of this problem on internet but nothing works.
I've used Rserve and Runtime.getRuntime().exec("Rscript myScript.R") but neither of them works with my program.
When I use Rserve, I run Rserve(args="--no-save") on R console and Rconnection.eval("\myscript.R") on Java program and when I execute it, the program continues running without any response, no errors either and no stops. In fact when I try to execute a more simply R script, like calculate the mean or something like that, it works, but when I try to coerce a data.frame in a xts/zoo time series or just to load xts/zoo library first in my script, the program doesn't stop running and does nothing.
On the other hand, when I try to execute "Runtime.getRuntime().exec("Rscript myScript.R")" like appears in other similar post, nothing happens. The program looks to execute the script but it doesn't give me any result although stops running at least. Maybe it is because of Mac OS and that I couldn't indicate to Java what is the Rscript or R.app path, I don't really know.
Thank you very much in advance and I wish you could help me.
Javi.
The file code is:
public void Rconnection () {
RConnection c=new RConnection();
System.out.println("INFO : Trying to Connect to R");
c.parseAndEval("source(\"/scriptname.R\")");
System.out.println("Greeting from R:" + result.asString());
c.close();
}
And the R script is:
EU.df <- read.csv("/myinput.csv",header=T)
EU.xts <- xts(EU.df[,2:5],seq(as.Date("1970-01-02"),len=nrow(EU.df),by="day"))
write.csv(EU.df, file = "/myoutputfile.csv",row.names=FALSE)
Maybe it's because of some problems with R libraries or because of MAC OS.
Have you tried using JRI? That might "block" unlike RServe and give you better messages.
For example:
REngine re = new JRIEngine(new String[] { "--no-save" }, new RCallback(), false);
re.parseAndEval("source(\"/scriptname.R\")");
re.close();

Prevent “Send error report to Microsoft”

I'm working on java application which perform some Runtime sub-process on files, for some files I got error cause the Send error report to Microsoft window to appear ,I need to handle this error programmatically, without showing this window to user. Please can anyone help ?
To Suppress windows error reporting the .exe that is being invoked should not terminate with an unhandled exception. This only works if you have access to the source of the application.
Based on the WER Reference - you should use the Win32 API call WerAddExcludedApplication to add the specific .exe files that you are intending to ignore to the per-user ignore list - you could create a simple stub-application that allows you to add applications by name to the ignore list. Then when you invoke the application it does not trigger the error.
Similarly you could create another application to remove them using the WerRemoveExcludedApplication.
Alternatives are to use JNI/JNA to make a class to encapsulate this functionality rather than using Runtime.exec
Here is a simple example using Java Native Access (JNA), which is a simpler version of JNI (no C++ needed for the most part). Download the jna.jar and make it part of your project.
import com.sun.jna.Native;
import com.sun.jna.WString;
import com.sun.jna.win32.StdCallLibrary;
public class JNATest {
public interface CLibrary extends StdCallLibrary {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("wer.dll",
CLibrary.class);
int WerAddExcludedApplication(WString name, boolean global);
int WerRemoveExcludedApplication(WString name, boolean global);
}
public static void main(String[] args) {
CLibrary.INSTANCE.WerAddExcludedApplication(new WString("C:\\foo.exe"), false);
CLibrary.INSTANCE.WerRemoveExcludedApplication(new WString("C:\\foo.exe"), false);
}
}
Basically, replace the new WString(...) value with the name of the application that you are intending to ignore. It should be ignored for the purposes of windows error reporting at that point.
Bear in mind that the wer.dll is only on Windows Vista and newer, so if this is a problem, then you may need to edit the registry entries manually.
You can always use try-catch-finally statement:
try
{
some code here (the code that is causing the error);
}
catch (Exception x)
{
handle exception here;
}
It works for me...
EDIT Here is the link that can help you a little bit more:
http://www.exampledepot.com/egs/Java%20Language/TryCatch.html

Java DTrace bridge on OS X

I am trying to grab filesystem events on OS / Kernel level on OS X.
There are 2 requirements i have to follow. The first one is to do this in java as the whole project im developing for is written in java. The second one is that i have to find out when a document is opened.
For Linux I used inotify-java, but I can't find a good equivalent on OS X. Also the JNA doesn't provide a helpful binding. Currently I'm avoiding catching events by frequently calling the lsof program. This, however, is a bad solution.
Thanks for the help.
You can use dtrace on OSX, but since it needs root privileges it's not something you'd want to put into a runtime of a system.
In any case, you won't be able to do this in pure Java (any Java API would be a wrapper around some lower level C introspection, and if you're doing it kernel-wide, would need to be done as root).
If you just want to track when your program is opening files (as opposed to other files on the same system) then you can install your own Security Manager and implement the checkRead() family of methods, which should give you an idea of when accesses are happening.
import java.io.*;
public class Demo {
public static void main(String args[]) throws Exception {
System.setSecurityManager(new Sniffer());
File f = new File("/tmp/file");
new FileInputStream(f);
}
}
class Sniffer extends SecurityManager {
public void checkRead(String name) {
System.out.println("Opening " + name);
}
}

Categories

Resources