KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openi > stat > r > rserve > RServeClient


1 /*********************************************************************************
2  * The contents of this file are subject to the OpenI Public License Version 1.0
3  * ("License"); You may not use this file except in compliance with the
4  * License. You may obtain a copy of the License at
5  * http://www.openi.org/docs/LICENSE.txt
6  *
7  * Software distributed under the License is distributed on an "AS IS" basis,
8  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
9  * the specific language governing rights and limitations under the License.
10  *
11  * The Original Code is: OpenI Open Source
12  *
13  * The Initial Developer of the Original Code is Loyalty Matrix, Inc.
14  * Portions created by Loyalty Matrix, Inc. are
15  * Copyright (C) 2005 Loyalty Matrix, Inc.; All Rights Reserved.
16  *
17  * Contributor(s): ______________________________________.
18  *
19  ********************************************************************************/

20 package org.openi.stat.r.rserve;
21
22 import org.apache.log4j.*;
23 import org.openi.stat.r.RClient;
24 import org.rosuda.JRclient.*;
25 import java.util.*;
26 import java.io.*;
27 import java.io.IOException JavaDoc;
28 import org.openi.stat.r.RFunction;
29 import org.openi.stat.r.RFunctionParam;
30
31 /**
32  * @author Uddhab Pant <br>
33  * @version $Revision: 1.7 $ $Date: 2006/04/12 00:39:12 $ <br>
34  *
35  * This class executes R script.
36  *
37  */

38 public class RServeClient implements RClient {
39     private static Logger logger = Logger.getLogger(RServeClient.class);
40     private String JavaDoc serverIP;
41     private int serverPort;
42     // RServe connection
43

44
45     /**
46      * Initialize RServe
47      * @param rServerIP String
48      * @throws RSrvException
49      */

50     public RServeClient(String JavaDoc rServerIP, int serverPort) throws RSrvException {
51         logger.debug("IP:" + rServerIP);
52         this.serverIP = rServerIP;
53         this.serverPort = serverPort;
54
55     }
56
57     /**
58      * R executes script and saves files under output path
59      * @param function RFunction
60      * @param outputPath String
61      * @throws Exception
62      */

63
64     public void execute(RFunction function, String JavaDoc outputPath) throws Exception JavaDoc {
65
66         String JavaDoc script = generateScript(function);
67         logger.debug("Generated Script: " + script);
68         Rconnection rConnection = new Rconnection(serverIP, serverPort);
69         String JavaDoc scriptContent = getContent(function.getFile());
70         logger.debug("Executing R Script file");
71         rConnection.voidEval(scriptContent);
72
73         if (function.getDataSetFile() != null &&
74             !"".equals(function.getDataSetFile())) {
75             logger.debug("Sending dataSet file " + function.getDataSetFile() +
76                          " to the R server");
77             sendFileToServer(rConnection, function.getDataSetFile());
78         }
79
80         logger.debug(
81                 "Executing generated R Script to call method on uploaded R script");
82         REXP xp = rConnection.eval(script);
83
84         if (function.getDataSetFile() != null &&
85             !"".equals(function.getDataSetFile())) {
86             logger.debug("Removing dataSet file " + function.getDataSetFile() +
87                          " from the R server");
88             removeFileFromServer(rConnection, function.getDataSetFile());
89         }
90
91         Vector output = xp.asVector();
92         logger.debug("Saving " + output.size() +
93                      " file(s) are generated by the R script to path " +
94                      outputPath);
95         Iterator iter = output.iterator();
96
97         while (iter.hasNext()) {
98             REXP xpFile = (REXP) iter.next();
99             String JavaDoc file = xpFile.asString();
100             logger.info("downloading '" + file + "' from r server");
101             saveFileFromServer(rConnection, file, outputPath);
102             removeFileFromServer(rConnection, file);
103         }
104
105         logger.debug("closing R");
106         rConnection.close();
107
108     }
109
110     /**
111      * Generates R script by passing parameters as:
112      * <code>
113      * data <- read.delim("uploadedFilename.tab", header=TRUE, sep="\t")
114      * filenames <- rFunctionCall(dataFrame = data, graphicsDevice=jpeg, other=otherParam)
115      * </code>
116      * @param function RFunction
117      * @return String
118      *
119      */

120     private String JavaDoc generateScript(RFunction function) {
121         StringBuffer JavaDoc generatedScript = new StringBuffer JavaDoc();
122         String JavaDoc functionName = function.getName();
123         StringBuffer JavaDoc paramString = new StringBuffer JavaDoc();
124         Iterator iterator = function.getParams().iterator();
125
126         if (function.getDataSetFile() != null &&
127             !"".equals(function.getDataSetFile())) {
128             String JavaDoc dataSetFileName = new File(function.getDataSetFile()).
129                                      getName();
130             generatedScript.append("data <- read.delim(\"" + dataSetFileName +
131                                    "\", ");
132             generatedScript.append("header=TRUE, sep=\"\\t\")");
133             paramString.append("dataFrame=data");
134             paramString.append(", ");
135             generatedScript.append("\n");
136
137         } while (iterator.hasNext()) {
138             RFunctionParam param = (RFunctionParam) iterator.next();
139             String JavaDoc paramVal = "String".equals(param.getType()) ?
140                               "\"" + param.getValue() + "\"" : param.getValue();
141             String JavaDoc paramWithVal = param.getName() + " = " + paramVal;
142             paramString.append(paramWithVal);
143             paramString.append(",");
144         }
145
146         if (paramString.lastIndexOf(",") != -1) {
147             paramString.deleteCharAt(paramString.lastIndexOf(","));
148         }
149
150         generatedScript.append("filenames <- " + functionName + "(");
151         generatedScript.append(paramString.toString());
152         generatedScript.append(")");
153
154         return generatedScript.toString();
155     }
156
157     /**
158      * Reads R script file content
159      * @param file String
160      * @return String
161      * @throws IOException
162      */

163     private String JavaDoc getContent(String JavaDoc file) throws IOException JavaDoc {
164         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
165         BufferedReader input = new BufferedReader(new InputStreamReader(new
166                 FileInputStream(file)));
167         while (input.ready()) {
168             buffer.append(input.readLine());
169             buffer.append("\n");
170         }
171         return buffer.toString();
172     }
173
174     /**
175      * Sends file to R Server
176      * @param rConnection Rconnection
177      * @param fileName String
178      * @throws IOException
179      */

180     private void sendFileToServer(Rconnection rConnection, String JavaDoc fileName) throws
181             IOException JavaDoc {
182         File file = new File(fileName);
183         RFileOutputStream ros = rConnection.createFile(file.getName());
184
185         BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
186                 file));
187
188         byte[] buf = new byte[512];
189         int n = 0;
190
191         while ((n = bis.read(buf)) != -1) {
192             ros.write(buf, 0, n);
193         }
194
195         ros.flush();
196         ros.close();
197         bis.close();
198
199     }
200
201     /**
202      * Retrieves file from R server
203      * @param rConnection Rconnection
204      * @param fileName String
205      * @param pathToSave String
206      * @throws Exception
207      */

208     private void saveFileFromServer(Rconnection rConnection, String JavaDoc fileName,
209                                     String JavaDoc pathToSave) throws Exception JavaDoc {
210         RFileInputStream ris = rConnection.openFile(fileName);
211         FileOutputStream outs = new FileOutputStream(pathToSave + "/" +
212                 new File(fileName).getName());
213         byte[] buf = new byte[512];
214         int n = 0;
215         while ((n = ris.read(buf)) != -1) {
216             outs.write(buf, 0, n);
217         }
218         outs.flush();
219         ris.close();
220         outs.close();
221     }
222
223     /**
224      * Removes file from R server
225      * @param rConnection Rconnection
226      * @param file String
227      * @throws RSrvException
228      */

229     private void removeFileFromServer(Rconnection rConnection, String JavaDoc file) throws
230             RSrvException {
231         rConnection.removeFile(new File(file).getName());
232     }
233 }
234
Popular Tags