I have the follow Java code that uses Rcaller.
RCaller caller = new RCaller();
RCode code = new RCode();
caller.setRscriptExecutable("/usr/bin/Rscript");
code.addRCode("install.packages(\"bbmle\")");
caller.redirectROutputToConsole();
caller.runOnly();
Essentially, I'm trying to run Java code that installs an R package (because later I will run R code within Java that requires this package).
When I run this code, I get the following output in Java
Error:Loading required package: Runiversal
However, I do have the Runiversal package on my Mac. Any ideas what this means, and why I'm not actually seeing any R output of the install.packages method, which is normally quite verbose?
UPDATE: I should note that even simple code such as the following results in the same error:
code.addRCode("x = c(1,2,3)");
code.addRCode("y = c(2,3,5");
code.addRCode("x+y");
caller.redirectROutputToConsole();
caller.runOnly();
UPDATE: I should also mention that the following works great:
StringBuffer allCode = readFile("temp.R");
code.setCode(allCode);
double[] xvector = new double[]{1,3,5,3,2,4,5,6,7,8,9,21,22,25,27,25,34,39,31};
double[] yvector = new double[]{6,7,5,6,5,6,6,7,6,8,9,21,20,19,23,24,29,38,30};
code.addDoubleArray("X",xvector);
code.addDoubleArray("Y",yvector);
code.addRCode("fun(X,Y)");
temp.R:
fun = function(x,y) {
return(lm(y~x))
}
Java output:
Output:
Output:Call:
Output:lm(formula = y ~ x)
Output:
Output:Coefficients:
Output:(Intercept) x
Output: 2.445 0.825
Output:
R loads package from the libraries. If the library that you installed the Runiversal package into is not being searched by the R process started under Java, that could result in the error message you're seeing.
So: what is the directory path (i.e., library) that the Runiversal package is installed in? Possibly related to this is what user installed the R package, and what user is running the Java code.
The 2.2 version of RCaller library does not require the R package Runiversal. A compact version of R to XML converters are implemented in the package. Try it out here
Related
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.
When I try to load the Nashorn compatibility file for Rhino (load("nashorn:mozilla_compat.js")) it comes up with the following error:
java.lang.RuntimeException: javax.script.ScriptException: ReferenceError: "net" is not defined in nashorn:mozilla_compat.js at line number 67
I've tried everything to get it to work but nothing has helped :(
This can happen if your script (not mozilla_compat.js itself) contains a declaration with a qualified name like this:
var x = new net.yourdomain.yourpackage.ClassName();
instead of doing
importPackage(Packages.net.yourdomain.yourpackage);
var x = new ClassName();
The former works in Rhino, but not in Nashorn, even with the compatibility script. The latter however will work in both environments.
I ran the following code with the latest JDK 8 update released (8u60) - available for download # http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
import javax.script.*;
public class Main {
public static void main(String[] ar) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
e.eval("load('nashorn:mozilla_compat.js')");
// this should print 'function' and mozilla_compat.js defines that function
e.eval("print(typeof importClass)");
}
}
And it printed "function" as expected. I checked it on jdk9-dev tip forest build as well. It works with that version as well. Will you please print "java -version" and make sure you're using recent JDK 8 ?
I'm working on a Windows 7 machine with R 3.1.0. I downloaded rcaller 2.2 and the latest 2.3 and followed the example of Sequential Commands in the tutorial. However, the program does not stop in Eclipse after the last line of code is executed.
The R.exe and Rterm.exe are still in the task manager. And every time I re-run the program, another R.exe and Rterm.exe are added in the task manager...
The following is the Java code:
import rcaller.RCaller;
import rcaller.RCode;
public class RCallerOnlineTest {
public static void main(String[] args) {
RCaller caller = new RCaller();
// change to your path please
caller.setRExecutable("C:/R/R-3.1.0/bin/x64/R.exe");
RCode code = new RCode();
caller.setRCode(code);
code.addDoubleArray("x", new double[]{1.0, 2.0, 3.0, 4.0, 50.0});
code.addRCode("result <- mean(x)");
caller.runAndReturnResultOnline("result");
double mean = caller.getParser().getAsDoubleArray("result")[0];
System.out.println("mean: " + mean);
boolean status = caller.stopStreamConsumers();
System.out.println(status);
}
}
The output is the following:
mean: 12.0
true
So the last print out true. I assume that it indicates rcaller is stopped, but it's not. Am I missing something here? I couldn't find a method called stop in the library...
Thank you for your post. The revision 59bfd7335cb8 fixes this problem, at least I hope.
The method StopRCallerOnline() in class RCaller now stops the R instance in the
memory which is created in runAndReturnResultOnline(). All test files passed and there are no R processes still stay in the task manager.
After more comprehensive tests, I plan to compile and publish the version 2.4 in 15th June.
But you are still able to download the source tree and compile yourself using maven
Hope works for you.
My aim is to call a Web Service from Java, initiated from a RPG function. (I know, its long way around, but it is what we need)
I have created a /JavaLib folder on the AS400, and copied all our needed External Jars we need.
Create a Java class with a static method WebServiceCaller.Call() to call a Web Service. When ever I run my RPG program everything is fine unto the RPG calls this method.
I get a Java exception:
Message . . . . : Java exception received when calling Java method (C G D
F).
Cause . . . . . : RPG procedure WEBSERCALR in program WAL60326/WEBSERCALR
received Java exception "java.lang.NoClassDefFoundError:
javax.xml.rpc.ServiceException" when calling method "Call" with signature
"(LwebService.Input;)LwebService.Output;" in class
"webService.WebServiceCaller".
CLASSPATH variable:
/JavaLib:/home/WAL60326/WebServiceCaller
So I believe my RPG and Java Class is fine, and I believe I have setup my CLASSPATH variable right. Not sure what else there is to check.
Update
So the jar file I need is jaxrpc.jar I have checked; it does exists in my /JavaLib.
Was able to check my Java version on the AS400 java version "1.5.0". And follow these instructions to check that my OS is V6R1.
Could it be my Java version that is out of date, for this Jar file to be loaded/work? Is that even a possibility?
Edit
Here is my source code:
Java: WebServiceCaller.Java
package webService;
import java.rmi.RemoteException;
import stocklistGetBids.GetBidsProxy;
public class WebServiceCaller {
public static Output Call(Input in) { // Input Class, is just a way to hold all the input together
Output out = null; // Output Class, holds all the output together
try {
GetBidsProxy getBidsProxy = new GetBidsProxy(); // GetBidsProxy generated by Eclipse
out = new Output(getBidsProxy.getBids(in.LogKey, in.Id));
} catch (RemoteException e) {
e.printStackTrace();
out = new Output("ERR");
}
return out;
}
}
Take note that the GetBidsProxy class in generated by Eclipse. And the Java side works well on my Windows Machine. Just not on the AS400 Machine.
RPG: WEBSERCALR.RPGLE
H DFTACTGRP(*NO)
H thread(*serialize)
D WebsercalInput DS
D ReturnCode 7A
D LogKey 20A
D ID 20A
D jString S O CLASS(*JAVA:'java.lang.String')
D jLogKey S O CLASS(*JAVA:'java.lang.String')
D jID S O CLASS(*JAVA:'java.lang.String')
D Input S O CLASS(*JAVA:'webService.Input')
D Output S O CLASS(*JAVA:'webService.Output')
D new_Input PR O EXTPROC(*JAVA:
D 'webService.Input':
D *CONSTRUCTOR)
D LogKey like(jString)
D ID like(jString)
D new_String PR O EXTPROC(*JAVA:
D 'java.lang.String':
D *CONSTRUCTOR)
D bytes 30A CONST VARYING
D Call PR like(Output)
D EXTPROC(*JAVA:
D 'webService.WebServiceCaller':
D 'Call')
D STATIC
D in like(Input)
D getReturnStat PR O EXTPROC(*JAVA:
D 'webService.Output':
D 'getReturnedStatus')
D CLASS(*JAVA:'java.lang.String')
D getBytes PR 65535A VARYING
D EXTPROC(*JAVA:
D 'java.lang.String':
D 'getBytes')
C *ENTRY PLIST
C PARM WebsercalInput
/free
jLogKey = new_String(LogKey);
jID = new_String(ID);
Input = new_Input(jLogKey:jID);
Output = Call(Input);
jString = getReturnStat(Output);
ReturnCode = getBytes(jString);
return;
/End-Free
The CLASSPATH is read only once for a given job, the first time you invoke the java command and the JVM starts. If your CLASSPATH changes after that, the JVM won't see or use the new CLASSPATH. Sign off and on (to start a new job), set the CLASSPATH (I do it in my signon program) and then try to use the class you're working with.
If the CLASSPATH is correct then the other thing to check is the Java prototype in your RPG program. It needs to exactly match the Java class definition.
First, make 100% certain that your jaxrpc.jar has all the classes you think it should. Start QShell, then java tf /JavaLib/jaxrpc.jar. Make sure you have at least these:
javax/xml/rpc/Call.class
javax/xml/rpc/ServiceFactory.class
javax/xml/rpc/ServiceException.class
Next, do a simple proof of concept program in pure Java to make sure all of the pieces work as you expect them to. Note: JAX-RPC is obsolete and goes away in Java 1.6 and up. It's been replaced by JAX-WS. If this is a brand new app, consider using the more current implementation. This 2006 DeveloperWorks article explains some of the differences.
Once you have a pure Java program written, it's time to take the Java classes that you used and prototype them in RPG. Assuming you've done all of that, could you edit your question to show the RPG *CLASS prototypes and the RPG code used to invoke them. Basically, see if someone reading this question can re-create the set-up on a different box.
I've used some Java in my RPG code and I found out that it's not enough to add the container folder to the CLASSPATH. I had to identify the individual jars in the CLASSPATH.
I am trying to build a java project which contains R codes. Main logic behind that is I want to automate the data structuring and data analysis with in a same project. Partially I am being able to do that. I connected R to Java and my R codes are running well. I did all my set up in the local machine and its giving me all output as I need. As data set is big I am trying to run this on amazon server. But when I am shifting it to server, my project is not working properly. Its not being able to execute library(XLConnect), library(rJava). When ever I am calling this two libraries in my java project it's crashing. Independently in R codes are running and giving me output. What I can I for that, and how to fix thus error. Please help me out from this.
My java codes is
import java.io.InputStreamReader;
import java.io.Reader;
public class TestRMain {
public static void main(String[] arg)throws Exception{
ProcessBuilder broker = new ProcessBuilder("R.exe","--file=E:\\New\\Modified_Best_Config.R");
Process runBroker = broker.start();
Reader reader = new InputStreamReader(runBroker.getInputStream());
int ch;
while((ch = reader.read())!= -1)
System.out.print((char)ch);
reader.close();
runBroker.waitFor();
System.out.println("Execution complete");
}
}
And in the Modified_Best_Config.R I have written these codes
library('ClustOfVar');
library("doBy");
library(XLConnect)
#library(rJava)
#library(xlsx)
path="E:/New/";
############Importing and reading the excel files into R##############
Automated_R <- loadWorkbook("E:/New/Option_Mix_Calculation1.xlsx")
sheet1 <- readWorksheet(Automated_R, sheet = "Current Output")
sheet2 <- readWorksheet(Automated_R, sheet = "Actual Sales monthly")
sheet3 <- readWorksheet(Automated_R, sheet = "Differences")
#####################Importing raw Data###############################
optionData<- read.csv(paste(path,"ModifiedStructureNewBestConfig1.csv",sep=""),head=TRUE,sep=",");
nrow(optionData)
optionDemand=sapply(split(optionData,optionData$Trim),trimSplit);
optionDemand1=t(optionDemand[c(-1,-2),]);
optionDemand1
################Calculating the equipment Demand####################
optionDemand2<-t(optionDemand2[c(-1,0)]);
Rownames <- as.data.frame(row.names(optionDemand2))
writeWorksheet(Automated_R,Rownames, sheet = "Current Output", startRow = 21, startCol = 1)
writeWorksheet(Automated_R,optionDemand2, sheet = "Current Output", startRow = 21, startCol = 2)
saveWorkbook(Automated_R)
But java is stopping its operation after these line.
library("doBy");
Whole set of codes are running on nicely on my local machine. But whenever I am trying to run this on amazon server it's not running. Individually in R this code is running on server. I have couple of more R codes which are running with out any error. What can I do for that, please help me out.
Thanks for updating your question with some example code. I cannot completely replicate your circumstances because I presently don't have immediate access to Amazon EC2, and I don't know the specific type of instance you are using. But here a couple of suggestions for de-bugging your issue, which I have a hunch is being caused by a missing package.
1. Try to install the offending packages via your R script
At the very beginning of your R script, before you try to load any packages, insert the following:
install.packages(c("XLConnect", "rJava"))
If your instance includes a specified CRAN mirror (essentially, the online repository where R will first look to download the package source code from), this should install the packages in the same repo where your other packages are kept on your server. Then, either library or require should load your packages.
(sidenote: rJava is actually a dependency of XLConnect, so it will automatically load anyway if you only specify library(XLConnect))
2. If the above does not work, try installing the packages via the command line
This is essentially what #Ben was suggesting with his comment. Alternatively, see perhaps this link, which deals with a similar problem with a different package. If you can, in terminal on the server, I would try entering the following three commands:
sudo add-apt-repository ppa:marutter/rrutter
sudo apt-get update
sudo apt-get install r-cran-XLConnect
In my experience this has been a good go-to repo when I can't seem to find a package I need to install. But you may or may not have permission to install packages on your server instance.