2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.ext.pymol;
23 import java.io.BufferedReader;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.io.InputStreamReader;
28 import java.io.PrintWriter;
29 import java.net.HttpURLConnection;
30 import java.net.SocketException;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.List;
36 import jalview.bin.Cache;
37 import jalview.bin.Console;
38 import jalview.gui.Preferences;
39 import jalview.structure.StructureCommand;
40 import jalview.structure.StructureCommandI;
42 public class PymolManager
44 private static final int RPC_REPLY_TIMEOUT_MS = 15000;
46 private static final int CONNECTION_TIMEOUT_MS = 100;
48 private static final String POST1 = "<methodCall><methodName>";
50 private static final String POST2 = "</methodName><params>";
52 private static final String POST3 = "</params></methodCall>";
54 private Process pymolProcess;
56 private int pymolXmlRpcPort;
59 * Returns a list of paths to try for the PyMOL executable. Any user
60 * preference is placed first, otherwise 'standard' paths depending on the
65 public static List<String> getPymolPaths()
67 return getPymolPaths(System.getProperty("os.name"));
71 * Returns a list of paths to try for the PyMOL executable. Any user
72 * preference is placed first, otherwise 'standard' paths depending on the
76 * operating system as reported by environment variable
80 protected static List<String> getPymolPaths(String os)
82 List<String> pathList = new ArrayList<>();
84 String userPath = Cache.getDefault(Preferences.PYMOL_PATH, null);
87 pathList.add(userPath);
91 * add default installation paths
93 String pymol = "PyMOL";
94 if (os.startsWith("Linux"))
96 pathList.add("/usr/local/pymol/bin/" + pymol);
97 pathList.add("/usr/local/bin/" + pymol);
98 pathList.add("/usr/bin/" + pymol);
99 pathList.add(System.getProperty("user.home") + "/opt/bin/" + pymol);
101 else if (os.startsWith("Windows"))
103 // todo Windows installation path(s)
105 else if (os.startsWith("Mac"))
107 pathList.add("/Applications/PyMOL.app/Contents/MacOS/" + pymol);
112 public boolean isPymolLaunched()
114 // TODO pull up generic methods for external viewer processes
115 boolean launched = false;
116 if (pymolProcess != null)
120 pymolProcess.exitValue();
121 // if we get here, process has ended
122 } catch (IllegalThreadStateException e)
124 // ok - not yet terminated
132 * Sends the command to Pymol; if requested, tries to get and return any
133 * replies, else returns null
139 public List<String> sendCommand(StructureCommandI command,
142 String postBody = getPostRequest(command);
143 // System.out.println(postBody);// debug
144 String rpcUrl = "http://127.0.0.1:" + this.pymolXmlRpcPort;
145 PrintWriter out = null;
146 BufferedReader in = null;
147 List<String> result = getReply ? new ArrayList<>() : null;
151 URL realUrl = new URL(rpcUrl);
152 HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
153 conn.setRequestProperty("accept", "*/*");
154 conn.setRequestProperty("content-type", "text/xml");
155 conn.setDoOutput(true);
156 conn.setDoInput(true);
157 out = new PrintWriter(conn.getOutputStream());
160 int rc = conn.getResponseCode();
161 if (rc != HttpURLConnection.HTTP_OK)
164 String.format("Error status from %s: %d", rpcUrl, rc));
168 InputStream inputStream = conn.getInputStream();
171 in = new BufferedReader(new InputStreamReader(inputStream));
173 while ((line = in.readLine()) != null)
178 } catch (SocketException e)
180 // thrown when 'quit' command is sent to PyMol
181 Console.warn(String.format("Request to %s returned %s", rpcUrl,
183 } catch (Exception e)
192 if (Console.isTraceEnabled())
194 Console.trace("Sent: " + command.toString());
197 Console.trace("Received: " + result);
205 * Builds the body of the XML-RPC format POST request to execute the command
210 static String getPostRequest(StructureCommandI command)
212 StringBuilder sb = new StringBuilder(64);
213 sb.append(POST1).append(command.getCommand()).append(POST2);
214 if (command.hasParameters())
216 for (String p : command.getParameters())
219 * for now assuming all are string - <string> element is optional
220 * refactor in future if other data types needed
221 * https://www.tutorialspoint.com/xml-rpc/xml_rpc_data_model.htm
223 sb.append("<parameter><value>").append(p)
224 .append("</value></parameter>");
228 return sb.toString();
231 public Process launchPymol()
233 // todo pull up much of this
234 // Do nothing if already launched
235 if (isPymolLaunched())
240 String error = "Error message: ";
241 for (String pymolPath : getPymolPaths())
245 // ensure symbolic links are resolved
246 pymolPath = Paths.get(pymolPath).toRealPath().toString();
247 File path = new File(pymolPath);
248 // uncomment the next line to simulate Pymol not installed
249 // path = new File(pymolPath + "x");
250 if (!path.canExecute())
252 error += "File '" + path + "' does not exist.\n";
255 List<String> args = new ArrayList<>();
257 args.add("-R"); // https://pymolwiki.org/index.php/RPC
258 ProcessBuilder pb = new ProcessBuilder(args);
259 pymolProcess = pb.start();
262 } catch (Exception e)
264 // Pymol could not be started using this path
265 error += e.getMessage();
269 if (pymolProcess != null)
271 this.pymolXmlRpcPort = getPortNumber();
272 if (pymolXmlRpcPort > 0)
274 Console.info("PyMOL XMLRPC started on port " + pymolXmlRpcPort);
278 error += "Failed to read PyMOL XMLRPC port number";
279 Console.error(error);
280 pymolProcess.destroy();
288 private int getPortNumber()
290 // TODO pull up most of this!
292 InputStream readChan = pymolProcess.getInputStream();
293 BufferedReader lineReader = new BufferedReader(
294 new InputStreamReader(readChan));
295 StringBuilder responses = new StringBuilder();
298 String response = lineReader.readLine();
299 while (response != null)
301 responses.append("\n" + response);
302 // expect: xml-rpc server running on host localhost, port 9123
303 if (response.contains("xml-rpc"))
305 String[] tokens = response.split(" ");
306 for (int i = 0; i < tokens.length - 1; i++)
308 if ("port".equals(tokens[i]))
310 port = Integer.parseInt(tokens[i + 1]);
317 break; // hack for hanging readLine()
319 response = lineReader.readLine();
321 } catch (Exception e)
323 Console.error("Failed to get REST port number from " + responses
324 + ": " + e.getMessage());
325 // logger.error("Failed to get REST port number from " + responses + ": "
326 // + e.getMessage());
332 } catch (IOException e2)
338 Console.error("Failed to start PyMOL with XMLRPC, response was: "
341 Console.info("PyMOL started with XMLRPC on port " + port);