JAL-3091 changed release date to 10th September - tweaked release notes.
[jalview.git] / src / ext / edu / ucsf / rbvi / strucviz2 / ChimeraManager.java
1 /* vim: set ts=2: */
2 /**
3  * Copyright (c) 2006 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *   1. Redistributions of source code must retain the above copyright
10  *      notice, this list of conditions, and the following disclaimer.
11  *   2. Redistributions in binary form must reproduce the above
12  *      copyright notice, this list of conditions, and the following
13  *      disclaimer in the documentation and/or other materials provided
14  *      with the distribution.
15  *   3. Redistributions must acknowledge that this software was
16  *      originally developed by the UCSF Computer Graphics Laboratory
17  *      under support by the NIH National Center for Research Resources,
18  *      grant P41-RR01081.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
21  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
26  * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
27  * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
28  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
29  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
30  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  */
33 package ext.edu.ucsf.rbvi.strucviz2;
34
35 import jalview.ws.HttpClientUtils;
36
37 import java.awt.Color;
38 import java.io.BufferedReader;
39 import java.io.File;
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.InputStreamReader;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.HashMap;
46 import java.util.List;
47 import java.util.Map;
48
49 import org.apache.http.NameValuePair;
50 import org.apache.http.message.BasicNameValuePair;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 import ext.edu.ucsf.rbvi.strucviz2.StructureManager.ModelType;
55 import ext.edu.ucsf.rbvi.strucviz2.port.ListenerThreads;
56
57 /**
58  * This object maintains the Chimera communication information.
59  */
60 public class ChimeraManager
61 {
62   private static final int REST_REPLY_TIMEOUT_MS = 15000;
63
64   private static final int CONNECTION_TIMEOUT_MS = 100;
65
66   private static final boolean debug = false;
67
68   private int chimeraRestPort;
69
70   private Process chimera;
71
72   private ListenerThreads chimeraListenerThread;
73
74   private Map<Integer, ChimeraModel> currentModelsMap;
75
76   private Logger logger = LoggerFactory
77           .getLogger(ext.edu.ucsf.rbvi.strucviz2.ChimeraManager.class);
78
79   private StructureManager structureManager;
80
81   public ChimeraManager(StructureManager structureManager)
82   {
83     this.structureManager = structureManager;
84     chimera = null;
85     chimeraListenerThread = null;
86     currentModelsMap = new HashMap<Integer, ChimeraModel>();
87
88   }
89
90   public List<ChimeraModel> getChimeraModels(String modelName)
91   {
92     List<ChimeraModel> models = getChimeraModels(modelName,
93             ModelType.PDB_MODEL);
94     models.addAll(getChimeraModels(modelName, ModelType.SMILES));
95     return models;
96   }
97
98   public List<ChimeraModel> getChimeraModels(String modelName,
99           ModelType modelType)
100   {
101     List<ChimeraModel> models = new ArrayList<ChimeraModel>();
102     for (ChimeraModel model : currentModelsMap.values())
103     {
104       if (modelName.equals(model.getModelName())
105               && modelType.equals(model.getModelType()))
106       {
107         models.add(model);
108       }
109     }
110     return models;
111   }
112
113   public Map<String, List<ChimeraModel>> getChimeraModelsMap()
114   {
115     Map<String, List<ChimeraModel>> models = new HashMap<String, List<ChimeraModel>>();
116     for (ChimeraModel model : currentModelsMap.values())
117     {
118       String modelName = model.getModelName();
119       if (!models.containsKey(modelName))
120       {
121         models.put(modelName, new ArrayList<ChimeraModel>());
122       }
123       if (!models.get(modelName).contains(model))
124       {
125         models.get(modelName).add(model);
126       }
127     }
128     return models;
129   }
130
131   public ChimeraModel getChimeraModel(Integer modelNumber,
132           Integer subModelNumber)
133   {
134     Integer key = ChimUtils.makeModelKey(modelNumber, subModelNumber);
135     if (currentModelsMap.containsKey(key))
136     {
137       return currentModelsMap.get(key);
138     }
139     return null;
140   }
141
142   public ChimeraModel getChimeraModel()
143   {
144     return currentModelsMap.values().iterator().next();
145   }
146
147   public Collection<ChimeraModel> getChimeraModels()
148   {
149     // this method is invoked by the model navigator dialog
150     return currentModelsMap.values();
151   }
152
153   public int getChimeraModelsCount(boolean smiles)
154   {
155     // this method is invokes by the model navigator dialog
156     int counter = currentModelsMap.size();
157     if (smiles)
158     {
159       return counter;
160     }
161
162     for (ChimeraModel model : currentModelsMap.values())
163     {
164       if (model.getModelType() == ModelType.SMILES)
165       {
166         counter--;
167       }
168     }
169     return counter;
170   }
171
172   public boolean hasChimeraModel(Integer modelNubmer)
173   {
174     return hasChimeraModel(modelNubmer, 0);
175   }
176
177   public boolean hasChimeraModel(Integer modelNubmer, Integer subModelNumber)
178   {
179     return currentModelsMap.containsKey(ChimUtils.makeModelKey(modelNubmer,
180             subModelNumber));
181   }
182
183   public void addChimeraModel(Integer modelNumber, Integer subModelNumber,
184           ChimeraModel model)
185   {
186     currentModelsMap.put(
187             ChimUtils.makeModelKey(modelNumber, subModelNumber), model);
188   }
189
190   public void removeChimeraModel(Integer modelNumber, Integer subModelNumber)
191   {
192     int modelKey = ChimUtils.makeModelKey(modelNumber, subModelNumber);
193     if (currentModelsMap.containsKey(modelKey))
194     {
195       currentModelsMap.remove(modelKey);
196     }
197   }
198
199   public List<ChimeraModel> openModel(String modelPath, ModelType type)
200   {
201     return openModel(modelPath, getFileNameFromPath(modelPath), type);
202   }
203
204   /**
205    * Overloaded method to allow Jalview to pass in a model name.
206    * 
207    * @param modelPath
208    * @param modelName
209    * @param type
210    * @return
211    */
212   public List<ChimeraModel> openModel(String modelPath, String modelName,
213           ModelType type)
214   {
215     logger.info("chimera open " + modelPath);
216     // stopListening();
217     List<ChimeraModel> modelList = getModelList();
218     List<String> response = null;
219     // TODO: [Optional] Handle modbase models
220     if (type == ModelType.MODBASE_MODEL)
221     {
222       response = sendChimeraCommand("open modbase:" + modelPath, true);
223       // } else if (type == ModelType.SMILES) {
224       // response = sendChimeraCommand("open smiles:" + modelName, true);
225       // modelName = "smiles:" + modelName;
226     }
227     else
228     {
229       response = sendChimeraCommand("open " + modelPath, true);
230     }
231     if (response == null)
232     {
233       // something went wrong
234       logger.warn("Could not open " + modelPath);
235       return null;
236     }
237
238     // patch for Jalview - set model name in Chimera
239     // TODO: find a variant that works for sub-models
240     for (ChimeraModel newModel : getModelList())
241     {
242       if (!modelList.contains(newModel))
243       {
244         newModel.setModelName(modelName);
245         sendChimeraCommand(
246                 "setattr M name " + modelName + " #"
247                         + newModel.getModelNumber(), false);
248         modelList.add(newModel);
249       }
250     }
251
252     // assign color and residues to open models
253     for (ChimeraModel chimeraModel : modelList)
254     {
255       // get model color
256       Color modelColor = getModelColor(chimeraModel);
257       if (modelColor != null)
258       {
259         chimeraModel.setModelColor(modelColor);
260       }
261
262       // Get our properties (default color scheme, etc.)
263       // Make the molecule look decent
264       // chimeraSend("repr stick "+newModel.toSpec());
265
266       // Create the information we need for the navigator
267       if (type != ModelType.SMILES)
268       {
269         addResidues(chimeraModel);
270       }
271     }
272
273     sendChimeraCommand("focus", false);
274     // startListening(); // see ChimeraListener
275     return modelList;
276   }
277
278   /**
279    * Refactored method to extract the last (or only) element delimited by file
280    * path separator.
281    * 
282    * @param modelPath
283    * @return
284    */
285   private String getFileNameFromPath(String modelPath)
286   {
287     String modelName = modelPath;
288     if (modelPath == null)
289     {
290       return null;
291     }
292     // TODO: [Optional] Convert path to name in a better way
293     if (modelPath.lastIndexOf(File.separator) > 0)
294     {
295       modelName = modelPath
296               .substring(modelPath.lastIndexOf(File.separator) + 1);
297     }
298     else if (modelPath.lastIndexOf("/") > 0)
299     {
300       modelName = modelPath.substring(modelPath.lastIndexOf("/") + 1);
301     }
302     return modelName;
303   }
304
305   public void closeModel(ChimeraModel model)
306   {
307     // int model = structure.modelNumber();
308     // int subModel = structure.subModelNumber();
309     // Integer modelKey = makeModelKey(model, subModel);
310     stopListening();
311     logger.info("chimera close model " + model.getModelName());
312     if (currentModelsMap.containsKey(ChimUtils.makeModelKey(
313             model.getModelNumber(), model.getSubModelNumber())))
314     {
315       sendChimeraCommand("close " + model.toSpec(), false);
316       // currentModelNamesMap.remove(model.getModelName());
317       currentModelsMap.remove(ChimUtils.makeModelKey(
318               model.getModelNumber(), model.getSubModelNumber()));
319       // selectionList.remove(chimeraModel);
320     }
321     else
322     {
323       logger.warn("Could not find model " + model.getModelName()
324               + " to close.");
325     }
326     startListening();
327   }
328
329   public void startListening()
330   {
331     sendChimeraCommand("listen start models; listen start selection", false);
332   }
333
334   public void stopListening()
335   {
336     sendChimeraCommand("listen stop models ; listen stop selection ", false);
337   }
338
339   /**
340    * Tell Chimera we are listening on the given URI
341    * 
342    * @param uri
343    */
344   public void startListening(String uri)
345   {
346     sendChimeraCommand("listen start models url " + uri
347             + ";listen start select prefix SelectionChanged url " + uri,
348             false);
349   }
350
351   /**
352    * Select something in Chimera
353    * 
354    * @param command
355    *          the selection command to pass to Chimera
356    */
357   public void select(String command)
358   {
359     sendChimeraCommand("listen stop selection; " + command
360             + "; listen start selection", false);
361   }
362
363   public void focus()
364   {
365     sendChimeraCommand("focus", false);
366   }
367
368   public void clearOnChimeraExit()
369   {
370     chimera = null;
371     currentModelsMap.clear();
372     this.chimeraRestPort = 0;
373     structureManager.clearOnChimeraExit();
374   }
375
376   public void exitChimera()
377   {
378     if (isChimeraLaunched() && chimera != null)
379     {
380       sendChimeraCommand("stop really", false);
381       try
382       {
383         // TODO is this too violent? could it force close the process
384         // before it has done an orderly shutdown?
385         chimera.destroy();
386       } catch (Exception ex)
387       {
388         // ignore
389       }
390     }
391     clearOnChimeraExit();
392   }
393
394   public Map<Integer, ChimeraModel> getSelectedModels()
395   {
396     Map<Integer, ChimeraModel> selectedModelsMap = new HashMap<Integer, ChimeraModel>();
397     List<String> chimeraReply = sendChimeraCommand(
398             "list selection level molecule", true);
399     if (chimeraReply != null)
400     {
401       for (String modelLine : chimeraReply)
402       {
403         ChimeraModel chimeraModel = new ChimeraModel(modelLine);
404         Integer modelKey = ChimUtils.makeModelKey(
405                 chimeraModel.getModelNumber(),
406                 chimeraModel.getSubModelNumber());
407         selectedModelsMap.put(modelKey, chimeraModel);
408       }
409     }
410     return selectedModelsMap;
411   }
412
413   /**
414    * Sends a 'list selection level residue' command to Chimera and returns the
415    * list of selected atomspecs
416    * 
417    * @return
418    */
419   public List<String> getSelectedResidueSpecs()
420   {
421     List<String> selectedResidues = new ArrayList<String>();
422     List<String> chimeraReply = sendChimeraCommand(
423             "list selection level residue", true);
424     if (chimeraReply != null)
425     {
426       /*
427        * expect 0, 1 or more lines of the format
428        * residue id #0:43.A type GLY
429        * where we are only interested in the atomspec #0.43.A
430        */
431       for (String inputLine : chimeraReply)
432       {
433         String[] inputLineParts = inputLine.split("\\s+");
434         if (inputLineParts.length == 5)
435         {
436           selectedResidues.add(inputLineParts[2]);
437         }
438       }
439     }
440     return selectedResidues;
441   }
442
443   public void getSelectedResidues(
444           Map<Integer, ChimeraModel> selectedModelsMap)
445   {
446     List<String> chimeraReply = sendChimeraCommand(
447             "list selection level residue", true);
448     if (chimeraReply != null)
449     {
450       for (String inputLine : chimeraReply)
451       {
452         ChimeraResidue r = new ChimeraResidue(inputLine);
453         Integer modelKey = ChimUtils.makeModelKey(r.getModelNumber(),
454                 r.getSubModelNumber());
455         if (selectedModelsMap.containsKey(modelKey))
456         {
457           ChimeraModel model = selectedModelsMap.get(modelKey);
458           model.addResidue(r);
459         }
460       }
461     }
462   }
463
464   /**
465    * Return the list of ChimeraModels currently open. Warning: if smiles model
466    * name too long, only part of it with "..." is printed.
467    * 
468    * 
469    * @return List of ChimeraModel's
470    */
471   // TODO: [Optional] Handle smiles names in a better way in Chimera?
472   public List<ChimeraModel> getModelList()
473   {
474     List<ChimeraModel> modelList = new ArrayList<ChimeraModel>();
475     List<String> list = sendChimeraCommand("list models type molecule",
476             true);
477     if (list != null)
478     {
479       for (String modelLine : list)
480       {
481         ChimeraModel chimeraModel = new ChimeraModel(modelLine);
482         modelList.add(chimeraModel);
483       }
484     }
485     return modelList;
486   }
487
488   /**
489    * Return the list of depiction presets available from within Chimera. Chimera
490    * will return the list as a series of lines with the format: Preset type
491    * number "description"
492    * 
493    * @return list of presets
494    */
495   public List<String> getPresets()
496   {
497     ArrayList<String> presetList = new ArrayList<String>();
498     List<String> output = sendChimeraCommand("preset list", true);
499     if (output != null)
500     {
501       for (String preset : output)
502       {
503         preset = preset.substring(7); // Skip over the "Preset"
504         preset = preset.replaceFirst("\"", "(");
505         preset = preset.replaceFirst("\"", ")");
506         // string now looks like: type number (description)
507         presetList.add(preset);
508       }
509     }
510     return presetList;
511   }
512
513   public boolean isChimeraLaunched()
514   {
515     boolean launched = false;
516     if (chimera != null)
517     {
518       try
519       {
520         chimera.exitValue();
521         // if we get here, process has ended
522       } catch (IllegalThreadStateException e)
523       {
524         // ok - not yet terminated
525         launched = true;
526       }
527     }
528     return launched;
529   }
530
531   /**
532    * Launch Chimera, unless an instance linked to this object is already
533    * running. Returns true if chimera is successfully launched, or already
534    * running, else false.
535    * 
536    * @param chimeraPaths
537    * @return
538    */
539   public boolean launchChimera(List<String> chimeraPaths)
540   {
541     // Do nothing if Chimera is already launched
542     if (isChimeraLaunched())
543     {
544       return true;
545     }
546
547     // Try to launch Chimera (eventually using one of the possible paths)
548     String error = "Error message: ";
549     String workingPath = "";
550     // iterate over possible paths for starting Chimera
551     for (String chimeraPath : chimeraPaths)
552     {
553       File path = new File(chimeraPath);
554       // uncomment the next line to simulate Chimera not installed
555       // path = new File(chimeraPath + "x");
556       if (!path.canExecute())
557       {
558         error += "File '" + path + "' does not exist.\n";
559         continue;
560       }
561       try
562       {
563         List<String> args = new ArrayList<String>();
564         args.add(chimeraPath);
565         // shows Chimera output window but suppresses REST responses:
566         // args.add("--debug");
567         args.add("--start");
568         args.add("RESTServer");
569         ProcessBuilder pb = new ProcessBuilder(args);
570         chimera = pb.start();
571         error = "";
572         workingPath = chimeraPath;
573         break;
574       } catch (Exception e)
575       {
576         // Chimera could not be started
577         error += e.getMessage();
578       }
579     }
580     // If no error, then Chimera was launched successfully
581     if (error.length() == 0)
582     {
583       this.chimeraRestPort = getPortNumber();
584       System.out.println("Chimera REST API started on port "
585               + chimeraRestPort);
586       // structureManager.initChimTable();
587       structureManager.setChimeraPathProperty(workingPath);
588       // TODO: [Optional] Check Chimera version and show a warning if below 1.8
589       // Ask Chimera to give us updates
590       // startListening(); // later - see ChimeraListener
591       return (chimeraRestPort > 0);
592     }
593
594     // Tell the user that Chimera could not be started because of an error
595     logger.warn(error);
596     return false;
597   }
598
599   /**
600    * Read and return the port number returned in the reply to --start RESTServer
601    */
602   private int getPortNumber()
603   {
604     int port = 0;
605     InputStream readChan = chimera.getInputStream();
606     BufferedReader lineReader = new BufferedReader(new InputStreamReader(
607             readChan));
608     StringBuilder responses = new StringBuilder();
609     try
610     {
611       String response = lineReader.readLine();
612       while (response != null)
613       {
614         responses.append("\n" + response);
615         // expect: REST server on host 127.0.0.1 port port_number
616         if (response.startsWith("REST server"))
617         {
618           String[] tokens = response.split(" ");
619           if (tokens.length == 7 && "port".equals(tokens[5]))
620           {
621             port = Integer.parseInt(tokens[6]);
622             break;
623           }
624         }
625         response = lineReader.readLine();
626       }
627     } catch (Exception e)
628     {
629       logger.error("Failed to get REST port number from " + responses
630               + ": " + e.getMessage());
631     } finally
632     {
633       try
634       {
635         lineReader.close();
636       } catch (IOException e2)
637       {
638       }
639     }
640     if (port == 0)
641     {
642       System.err
643               .println("Failed to start Chimera with REST service, response was: "
644                       + responses);
645     }
646     logger.info("Chimera REST service listening on port " + chimeraRestPort);
647     return port;
648   }
649
650   /**
651    * Determine the color that Chimera is using for this model.
652    * 
653    * @param model
654    *          the ChimeraModel we want to get the Color for
655    * @return the default model Color for this model in Chimera
656    */
657   public Color getModelColor(ChimeraModel model)
658   {
659     List<String> colorLines = sendChimeraCommand(
660             "list model spec " + model.toSpec() + " attribute color", true);
661     if (colorLines == null || colorLines.size() == 0)
662     {
663       return null;
664     }
665     return ChimUtils.parseModelColor(colorLines.get(0));
666   }
667
668   /**
669    * 
670    * Get information about the residues associated with a model. This uses the
671    * Chimera listr command. We don't return the resulting residues, but we add
672    * the residues to the model.
673    * 
674    * @param model
675    *          the ChimeraModel to get residue information for
676    * 
677    */
678   public void addResidues(ChimeraModel model)
679   {
680     int modelNumber = model.getModelNumber();
681     int subModelNumber = model.getSubModelNumber();
682     // Get the list -- it will be in the reply log
683     List<String> reply = sendChimeraCommand(
684             "list residues spec " + model.toSpec(), true);
685     if (reply == null)
686     {
687       return;
688     }
689     for (String inputLine : reply)
690     {
691       ChimeraResidue r = new ChimeraResidue(inputLine);
692       if (r.getModelNumber() == modelNumber
693               || r.getSubModelNumber() == subModelNumber)
694       {
695         model.addResidue(r);
696       }
697     }
698   }
699
700   public List<String> getAttrList()
701   {
702     List<String> attributes = new ArrayList<String>();
703     final List<String> reply = sendChimeraCommand("list resattr", true);
704     if (reply != null)
705     {
706       for (String inputLine : reply)
707       {
708         String[] lineParts = inputLine.split("\\s");
709         if (lineParts.length == 2 && lineParts[0].equals("resattr"))
710         {
711           attributes.add(lineParts[1]);
712         }
713       }
714     }
715     return attributes;
716   }
717
718   public Map<ChimeraResidue, Object> getAttrValues(String aCommand,
719           ChimeraModel model)
720   {
721     Map<ChimeraResidue, Object> values = new HashMap<ChimeraResidue, Object>();
722     final List<String> reply = sendChimeraCommand("list residue spec "
723             + model.toSpec() + " attribute " + aCommand, true);
724     if (reply != null)
725     {
726       for (String inputLine : reply)
727       {
728         String[] lineParts = inputLine.split("\\s");
729         if (lineParts.length == 5)
730         {
731           ChimeraResidue residue = ChimUtils
732                   .getResidue(lineParts[2], model);
733           String value = lineParts[4];
734           if (residue != null)
735           {
736             if (value.equals("None"))
737             {
738               continue;
739             }
740             if (value.equals("True") || value.equals("False"))
741             {
742               values.put(residue, Boolean.valueOf(value));
743               continue;
744             }
745             try
746             {
747               Double doubleValue = Double.valueOf(value);
748               values.put(residue, doubleValue);
749             } catch (NumberFormatException ex)
750             {
751               values.put(residue, value);
752             }
753           }
754         }
755       }
756     }
757     return values;
758   }
759
760   private volatile boolean busy = false;
761
762   /**
763    * Send a command to Chimera.
764    * 
765    * @param command
766    *          Command string to be send.
767    * @param reply
768    *          Flag indicating whether the method should return the reply from
769    *          Chimera or not.
770    * @return List of Strings corresponding to the lines in the Chimera reply or
771    *         <code>null</code>.
772    */
773   public List<String> sendChimeraCommand(String command, boolean reply)
774   {
775    // System.out.println("chimeradebug>> " + command);
776     if (!isChimeraLaunched() || command == null
777             || "".equals(command.trim()))
778     {
779       return null;
780     }
781     // TODO do we need a maximum wait time before aborting?
782     while (busy)
783     {
784       try
785       {
786         Thread.sleep(25);
787       } catch (InterruptedException q)
788       {
789       }
790     }
791     busy = true;
792     long startTime = System.currentTimeMillis();
793     try
794     {
795       return sendRestCommand(command);
796     } finally
797     {
798       /*
799        * Make sure busy flag is reset come what may!
800        */
801       busy = false;
802       if (debug)
803       {
804         System.out.println("Chimera command took "
805                 + (System.currentTimeMillis() - startTime) + "ms: "
806                 + command);
807       }
808
809     }
810   }
811
812   /**
813    * Sends the command to Chimera's REST API, and returns any response lines.
814    * 
815    * @param command
816    * @return
817    */
818   protected List<String> sendRestCommand(String command)
819   {
820     String restUrl = "http://127.0.0.1:" + this.chimeraRestPort + "/run";
821     List<NameValuePair> commands = new ArrayList<NameValuePair>(1);
822     commands.add(new BasicNameValuePair("command", command));
823
824     List<String> reply = new ArrayList<String>();
825     BufferedReader response = null;
826     try
827     {
828       response = HttpClientUtils.doHttpUrlPost(restUrl, commands, CONNECTION_TIMEOUT_MS,
829               REST_REPLY_TIMEOUT_MS);
830       String line = "";
831       while ((line = response.readLine()) != null)
832       {
833         reply.add(line);
834       }
835     } catch (Exception e)
836     {
837       logger.error("REST call '" + command + "' failed: " + e.getMessage());
838     } finally
839     {
840       if (response != null)
841       {
842         try
843         {
844           response.close();
845         } catch (IOException e)
846         {
847         }
848       }
849     }
850     return reply;
851   }
852
853   /**
854    * Send a command to stdin of Chimera process, and optionally read any
855    * responses.
856    * 
857    * @param command
858    * @param readReply
859    * @return
860    */
861   protected List<String> sendStdinCommand(String command, boolean readReply)
862   {
863     chimeraListenerThread.clearResponse(command);
864     String text = command.concat("\n");
865     try
866     {
867       // send the command
868       chimera.getOutputStream().write(text.getBytes());
869       chimera.getOutputStream().flush();
870     } catch (IOException e)
871     {
872       // logger.info("Unable to execute command: " + text);
873       // logger.info("Exiting...");
874       logger.warn("Unable to execute command: " + text);
875       logger.warn("Exiting...");
876       clearOnChimeraExit();
877       return null;
878     }
879     if (!readReply)
880     {
881       return null;
882     }
883     List<String> rsp = chimeraListenerThread.getResponse(command);
884     return rsp;
885   }
886
887   public StructureManager getStructureManager()
888   {
889     return structureManager;
890   }
891
892   public boolean isBusy()
893   {
894     return busy;
895   }
896
897   public Process getChimeraProcess()
898   {
899     return chimera;
900   }
901 }