From: gmungoc Date: Thu, 30 Apr 2020 10:47:39 +0000 (+0100) Subject: JAL-3551 tidied error handling for HTTP request X-Git-Tag: Release_2_11_2_0~37^2~21 X-Git-Url: http://source.jalview.org/gitweb/?p=jalview.git;a=commitdiff_plain;h=6e0685c38078ddcf959db75d001f8c92b114c8ae JAL-3551 tidied error handling for HTTP request --- diff --git a/src/jalview/ext/pymol/PymolManager.java b/src/jalview/ext/pymol/PymolManager.java index ad44677..f410b54 100644 --- a/src/jalview/ext/pymol/PymolManager.java +++ b/src/jalview/ext/pymol/PymolManager.java @@ -1,22 +1,23 @@ package jalview.ext.pymol; -import jalview.bin.Cache; -import jalview.gui.Preferences; -import jalview.structure.StructureCommand; -import jalview.structure.StructureCommandI; - import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.SocketException; import java.net.URL; -import java.net.URLConnection; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; +import jalview.bin.Cache; +import jalview.gui.Preferences; +import jalview.structure.StructureCommand; +import jalview.structure.StructureCommandI; + public class PymolManager { private static final int RPC_REPLY_TIMEOUT_MS = 15000; @@ -120,11 +121,12 @@ public class PymolManager String rpcUrl = "http://127.0.0.1:" + this.pymolXmlRpcPort; PrintWriter out = null; BufferedReader in = null; - List result = new ArrayList<>(); + List result = getReply ? new ArrayList<>() : null; + try { URL realUrl = new URL(rpcUrl); - URLConnection conn = realUrl.openConnection(); + HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("content-type", "text/xml"); conn.setDoOutput(true); @@ -132,31 +134,38 @@ public class PymolManager out = new PrintWriter(conn.getOutputStream()); out.print(postBody); out.flush(); - in = new BufferedReader(new InputStreamReader(conn.getInputStream())); - String line; - while ((line = in.readLine()) != null) + int rc = conn.getResponseCode(); + if (rc != HttpURLConnection.HTTP_OK) { - result.add(line); + Cache.log.error( + String.format("Error status from %s: %d", rpcUrl, rc)); + return result; } + + InputStream inputStream = conn.getInputStream(); + if (getReply) + { + in = new BufferedReader(new InputStreamReader(inputStream)); + String line; + while ((line = in.readLine()) != null) + { + result.add(line); + } + } + } catch (SocketException e) + { + // thrown when 'quit' command is sent to PyMol + Cache.log.warn(String.format("Request to %s returned %s", rpcUrl, + e.toString())); } catch (Exception e) { e.printStackTrace(); } finally { - try - { - if (out != null) - { - out.close(); - } - if (in != null) - { - in.close(); - } - } catch (IOException ex) + if (out != null) { - ex.printStackTrace(); - } + out.close(); + } } return result; }