1 package jalview.ext.pymol;
3 import java.io.BufferedReader;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.PrintWriter;
9 import java.net.HttpURLConnection;
10 import java.net.SocketException;
12 import java.nio.file.Paths;
13 import java.util.ArrayList;
14 import java.util.List;
16 import jalview.bin.Cache;
17 import jalview.gui.Preferences;
18 import jalview.structure.StructureCommand;
19 import jalview.structure.StructureCommandI;
21 public class PymolManager
23 private static final int RPC_REPLY_TIMEOUT_MS = 15000;
25 private static final int CONNECTION_TIMEOUT_MS = 100;
27 private static final String POST1 = "<methodCall><methodName>";
29 private static final String POST2 = "</methodName><params>";
31 private static final String POST3 = "</params></methodCall>";
33 private Process pymolProcess;
35 private int pymolXmlRpcPort;
38 * Returns a list of paths to try for the PyMOL executable. Any user
39 * preference is placed first, otherwise 'standard' paths depending on the
44 public static List<String> getPymolPaths()
46 return getPymolPaths(System.getProperty("os.name"));
50 * Returns a list of paths to try for the PyMOL executable. Any user
51 * preference is placed first, otherwise 'standard' paths depending on the
55 * operating system as reported by environment variable
59 protected static List<String> getPymolPaths(String os)
61 List<String> pathList = new ArrayList<>();
63 String userPath = Cache
64 .getDefault(Preferences.PYMOL_PATH, null);
67 pathList.add(userPath);
71 * add default installation paths
73 String pymol = "PyMOL";
74 if (os.startsWith("Linux"))
76 pathList.add("/usr/local/pymol/bin/" + pymol);
77 pathList.add("/usr/local/bin/" + pymol);
78 pathList.add("/usr/bin/" + pymol);
79 pathList.add(System.getProperty("user.home") + "/opt/bin/" + pymol);
81 else if (os.startsWith("Windows"))
83 // todo Windows installation path(s)
85 else if (os.startsWith("Mac"))
87 pathList.add("/Applications/PyMOL.app/Contents/MacOS/" + pymol);
92 public boolean isPymolLaunched()
94 // TODO pull up generic methods for external viewer processes
95 boolean launched = false;
96 if (pymolProcess != null)
100 pymolProcess.exitValue();
101 // if we get here, process has ended
102 } catch (IllegalThreadStateException e)
104 // ok - not yet terminated
112 * Sends the command to Pymol; if requested, tries to get and return any
113 * replies, else returns null
119 public List<String> sendCommand(StructureCommandI command,
122 String postBody = getPostRequest(command);
123 // System.out.println(postBody);// debug
124 String rpcUrl = "http://127.0.0.1:" + this.pymolXmlRpcPort;
125 PrintWriter out = null;
126 BufferedReader in = null;
127 List<String> result = getReply ? new ArrayList<>() : null;
131 URL realUrl = new URL(rpcUrl);
132 HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
133 conn.setRequestProperty("accept", "*/*");
134 conn.setRequestProperty("content-type", "text/xml");
135 conn.setDoOutput(true);
136 conn.setDoInput(true);
137 out = new PrintWriter(conn.getOutputStream());
140 int rc = conn.getResponseCode();
141 if (rc != HttpURLConnection.HTTP_OK)
144 String.format("Error status from %s: %d", rpcUrl, rc));
148 InputStream inputStream = conn.getInputStream();
151 in = new BufferedReader(new InputStreamReader(inputStream));
153 while ((line = in.readLine()) != null)
158 } catch (SocketException e)
160 // thrown when 'quit' command is sent to PyMol
161 Cache.log.warn(String.format("Request to %s returned %s", rpcUrl,
163 } catch (Exception e)
177 * Builds the body of the XML-RPC format POST request to execute the command
182 static String getPostRequest(StructureCommandI command)
184 StringBuilder sb = new StringBuilder(64);
185 sb.append(POST1).append(command.getCommand()).append(POST2);
186 if (command.hasParameters())
188 for (String p : command.getParameters())
191 * for now assuming all are string - <string> element is optional
192 * refactor in future if other data types needed
193 * https://www.tutorialspoint.com/xml-rpc/xml_rpc_data_model.htm
195 sb.append("<parameter><value>").append(p)
196 .append("</value></parameter>");
200 return sb.toString();
203 public Process launchPymol()
205 // todo pull up much of this
206 // Do nothing if already launched
207 if (isPymolLaunched())
212 String error = "Error message: ";
213 for (String pymolPath : getPymolPaths())
217 // ensure symbolic links are resolved
218 pymolPath = Paths.get(pymolPath).toRealPath().toString();
219 File path = new File(pymolPath);
220 // uncomment the next line to simulate Pymol not installed
221 // path = new File(pymolPath + "x");
222 if (!path.canExecute())
224 error += "File '" + path + "' does not exist.\n";
227 List<String> args = new ArrayList<>();
229 args.add("-R"); // https://pymolwiki.org/index.php/RPC
230 ProcessBuilder pb = new ProcessBuilder(args);
231 pymolProcess = pb.start();
234 } catch (Exception e)
236 // Pymol could not be started using this path
237 error += e.getMessage();
241 if (pymolProcess != null)
243 this.pymolXmlRpcPort = getPortNumber();
244 if (pymolXmlRpcPort > 0)
246 Cache.log.info("PyMOL XMLRPC started on port " + pymolXmlRpcPort);
250 error += "Failed to read PyMOL XMLRPC port number";
251 Cache.log.error(error);
252 pymolProcess.destroy();
260 private int getPortNumber()
262 // TODO pull up most of this!
264 InputStream readChan = pymolProcess.getInputStream();
265 BufferedReader lineReader = new BufferedReader(
266 new InputStreamReader(readChan));
267 StringBuilder responses = new StringBuilder();
270 String response = lineReader.readLine();
271 while (response != null)
273 responses.append("\n" + response);
274 // expect: xml-rpc server running on host localhost, port 9123
275 if (response.contains("xml-rpc"))
277 String[] tokens = response.split(" ");
278 for (int i = 0; i < tokens.length - 1; i++)
280 if ("port".equals(tokens[i]))
282 port = Integer.parseInt(tokens[i + 1]);
289 break; // hack for hanging readLine()
291 response = lineReader.readLine();
293 } catch (Exception e)
295 Cache.log.error("Failed to get REST port number from " + responses
296 + ": " + e.getMessage());
297 // logger.error("Failed to get REST port number from " + responses + ": "
298 // + e.getMessage());
304 } catch (IOException e2)
310 Cache.log.error("Failed to start PyMOL with XMLRPC, response was: "
313 Cache.log.error("PyMOL started with XMLRPC on port " + port);