launcher/fx/src/main/java/org/apidesign/bck2brwsr/launcher/BaseHTTPLauncher.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 27 Jun 2013 10:05:00 +0200
branchclassloader
changeset 1235 36614e9273e9
parent 1188 4d324bf6ede9
child 1249 cdaeea7becf2
permissions -rw-r--r--
Old handlers are sometimes used even after remoteHttpHandler is called. Invalidate old handlers by forcing them to delegate to the latest one.
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.launcher;
    19 
    20 import java.io.ByteArrayInputStream;
    21 import java.io.Closeable;
    22 import java.io.File;
    23 import java.io.IOException;
    24 import java.io.InputStream;
    25 import java.io.InterruptedIOException;
    26 import java.io.OutputStream;
    27 import java.io.Reader;
    28 import java.io.UnsupportedEncodingException;
    29 import java.io.Writer;
    30 import java.net.URI;
    31 import java.net.URISyntaxException;
    32 import java.net.URL;
    33 import java.util.ArrayList;
    34 import java.util.Arrays;
    35 import java.util.Enumeration;
    36 import java.util.LinkedHashSet;
    37 import java.util.List;
    38 import java.util.Set;
    39 import java.util.concurrent.BlockingQueue;
    40 import java.util.concurrent.Callable;
    41 import java.util.concurrent.CountDownLatch;
    42 import java.util.concurrent.LinkedBlockingQueue;
    43 import java.util.concurrent.TimeUnit;
    44 import java.util.logging.Level;
    45 import java.util.logging.Logger;
    46 import org.apidesign.bck2brwsr.launcher.InvocationContext.Resource;
    47 import org.glassfish.grizzly.PortRange;
    48 import org.glassfish.grizzly.http.server.HttpHandler;
    49 import org.glassfish.grizzly.http.server.HttpServer;
    50 import org.glassfish.grizzly.http.server.NetworkListener;
    51 import org.glassfish.grizzly.http.server.Request;
    52 import org.glassfish.grizzly.http.server.Response;
    53 import org.glassfish.grizzly.http.server.ServerConfiguration;
    54 import org.glassfish.grizzly.http.util.HttpStatus;
    55 import org.glassfish.grizzly.threadpool.ThreadPoolConfig;
    56 
    57 /**
    58  * Lightweight server to launch Bck2Brwsr applications and tests.
    59  * Supports execution in native browser as well as Java's internal 
    60  * execution engine.
    61  */
    62 abstract class BaseHTTPLauncher extends Launcher implements Closeable, Callable<HttpServer> {
    63     static final Logger LOG = Logger.getLogger(BaseHTTPLauncher.class.getName());
    64     private static final InvocationContext END = new InvocationContext(null, null, null);
    65     private final Set<ClassLoader> loaders = new LinkedHashSet<ClassLoader>();
    66     private final BlockingQueue<InvocationContext> methods = new LinkedBlockingQueue<InvocationContext>();
    67     private long timeOut;
    68     private final Res resources = new Res();
    69     private final String cmd;
    70     private Object[] brwsr;
    71     private HttpServer server;
    72     private CountDownLatch wait;
    73     
    74     public BaseHTTPLauncher(String cmd) {
    75         this.cmd = cmd;
    76         addClassLoader(BaseHTTPLauncher.class.getClassLoader());
    77         setTimeout(180000);
    78     }
    79     
    80     @Override
    81     InvocationContext runMethod(InvocationContext c) throws IOException {
    82         loaders.add(c.clazz.getClassLoader());
    83         methods.add(c);
    84         try {
    85             c.await(timeOut);
    86         } catch (InterruptedException ex) {
    87             throw new IOException(ex);
    88         }
    89         return c;
    90     }
    91     
    92     public void setTimeout(long ms) {
    93         timeOut = ms;
    94     }
    95     
    96     public void addClassLoader(ClassLoader url) {
    97         this.loaders.add(url);
    98     }
    99     
   100     ClassLoader[] loaders() {
   101         return loaders.toArray(new ClassLoader[loaders.size()]);
   102     }
   103 
   104     public void showURL(String startpage) throws IOException {
   105         if (!startpage.startsWith("/")) {
   106             startpage = "/" + startpage;
   107         }
   108         HttpServer s = initServer(".", true);
   109         int last = startpage.lastIndexOf('/');
   110         String prefix = startpage.substring(0, last);
   111         String simpleName = startpage.substring(last);
   112         s.getServerConfiguration().addHttpHandler(new SubTree(resources, prefix), "/");
   113         server = s;
   114         try {
   115             launchServerAndBrwsr(s, simpleName);
   116         } catch (Exception ex) {
   117             throw new IOException(ex);
   118         }
   119     }
   120 
   121     void showDirectory(File dir, String startpage) throws IOException {
   122         if (!startpage.startsWith("/")) {
   123             startpage = "/" + startpage;
   124         }
   125         HttpServer s = initServer(dir.getPath(), false);
   126         try {
   127             launchServerAndBrwsr(s, startpage);
   128         } catch (Exception ex) {
   129             throw new IOException(ex);
   130         }
   131     }
   132 
   133     @Override
   134     public void initialize() throws IOException {
   135         try {
   136             executeInBrowser();
   137         } catch (InterruptedException ex) {
   138             final InterruptedIOException iio = new InterruptedIOException(ex.getMessage());
   139             iio.initCause(ex);
   140             throw iio;
   141         } catch (Exception ex) {
   142             if (ex instanceof IOException) {
   143                 throw (IOException)ex;
   144             }
   145             if (ex instanceof RuntimeException) {
   146                 throw (RuntimeException)ex;
   147             }
   148             throw new IOException(ex);
   149         }
   150     }
   151     
   152     private HttpServer initServer(String path, boolean addClasses) throws IOException {
   153         HttpServer s = HttpServer.createSimpleServer(path, new PortRange(8080, 65535));
   154 
   155         ThreadPoolConfig fewThreads = ThreadPoolConfig.defaultConfig().copy().
   156             setPoolName("Fx/Bck2 Brwsr").
   157             setCorePoolSize(1).
   158             setMaxPoolSize(5);
   159         ThreadPoolConfig oneKernel = ThreadPoolConfig.defaultConfig().copy().
   160             setPoolName("Kernel Fx/Bck2").
   161             setCorePoolSize(1).
   162             setMaxPoolSize(3);
   163         for (NetworkListener nl : s.getListeners()) {
   164             nl.getTransport().setWorkerThreadPoolConfig(fewThreads);
   165             nl.getTransport().setKernelThreadPoolConfig(oneKernel);
   166         }
   167         
   168         final ServerConfiguration conf = s.getServerConfiguration();
   169         if (addClasses) {
   170             conf.addHttpHandler(new VM(), "/bck2brwsr.js");
   171             conf.addHttpHandler(new Classes(resources), "/classes/");
   172         }
   173         return s;
   174     }
   175     
   176     private void executeInBrowser() throws InterruptedException, URISyntaxException, IOException {
   177         wait = new CountDownLatch(1);
   178         server = initServer(".", true);
   179         final ServerConfiguration conf = server.getServerConfiguration();
   180         
   181         class DynamicResourceHandler extends HttpHandler {
   182             private final InvocationContext ic;
   183             private int resourcesCount;
   184             DynamicResourceHandler delegate;
   185             public DynamicResourceHandler(InvocationContext ic) {
   186                 this.ic = ic;
   187                 for (Resource r : ic.resources) {
   188                     conf.addHttpHandler(this, r.httpPath);
   189                 }
   190             }
   191 
   192             public void close(DynamicResourceHandler del) {
   193                 conf.removeHttpHandler(this);
   194                 delegate = del;
   195             }
   196             
   197             @Override
   198             public void service(Request request, Response response) throws Exception {
   199                 if (delegate != null) {
   200                     delegate.service(request, response);
   201                     return;
   202                 }
   203                 
   204                 if ("/dynamic".equals(request.getRequestURI())) {
   205                     String mimeType = request.getParameter("mimeType");
   206                     List<String> params = new ArrayList<String>();
   207                     for (int i = 0; ; i++) {
   208                         String p = request.getParameter("param" + i);
   209                         if (p == null) {
   210                             break;
   211                         }
   212                         params.add(p);
   213                     }
   214                     final String cnt = request.getParameter("content");
   215                     String mangle = cnt.replace("%20", " ").replace("%0A", "\n");
   216                     ByteArrayInputStream is = new ByteArrayInputStream(mangle.getBytes("UTF-8"));
   217                     URI url = registerResource(new Resource(is, mimeType, "/dynamic/res" + ++resourcesCount, params.toArray(new String[params.size()])));
   218                     response.getWriter().write(url.toString());
   219                     response.getWriter().write("\n");
   220                     return;
   221                 }
   222                 
   223                 for (Resource r : ic.resources) {
   224                     if (r.httpPath.equals(request.getRequestURI())) {
   225                         LOG.log(Level.INFO, "Serving HttpResource for {0}", request.getRequestURI());
   226                         response.setContentType(r.httpType);
   227                         r.httpContent.reset();
   228                         String[] params = null;
   229                         if (r.parameters.length != 0) {
   230                             params = new String[r.parameters.length];
   231                             for (int i = 0; i < r.parameters.length; i++) {
   232                                 params[i] = request.getParameter(r.parameters[i]);
   233                                 if (params[i] == null) {
   234                                     if ("http.method".equals(r.parameters[i])) {
   235                                         params[i] = request.getMethod().toString();
   236                                     } else if ("http.requestBody".equals(r.parameters[i])) {
   237                                         Reader rdr = request.getReader();
   238                                         StringBuilder sb = new StringBuilder();
   239                                         for (;;) {
   240                                             int ch = rdr.read();
   241                                             if (ch == -1) {
   242                                                 break;
   243                                             }
   244                                             sb.append((char)ch);
   245                                         }
   246                                         params[i] = sb.toString();
   247                                     }
   248                                 }
   249                                 if (params[i] == null) {
   250                                     params[i] = "null";
   251                                 }
   252                             }
   253                         }
   254                         
   255                         copyStream(r.httpContent, response.getOutputStream(), null, params);
   256                     }
   257                 }
   258             }
   259 
   260             private URI registerResource(Resource r) {
   261                 if (!ic.resources.contains(r)) {
   262                     ic.resources.add(r);
   263                     conf.addHttpHandler(this, r.httpPath);
   264                 }
   265                 return pageURL(server, r.httpPath);
   266             }
   267         }
   268         
   269         conf.addHttpHandler(new Page(resources, harnessResource()), "/execute");
   270         
   271         conf.addHttpHandler(new HttpHandler() {
   272             int cnt;
   273             List<InvocationContext> cases = new ArrayList<InvocationContext>();
   274             DynamicResourceHandler prev;
   275             @Override
   276             public void service(Request request, Response response) throws Exception {
   277                 String id = request.getParameter("request");
   278                 String value = request.getParameter("result");
   279                 if (value != null && value.indexOf((char)0xC5) != -1) {
   280                     value = toUTF8(value);
   281                 }
   282                 
   283                 
   284                 InvocationContext mi = null;
   285                 int caseNmbr = -1;
   286                 
   287                 if (id != null && value != null) {
   288                     LOG.log(Level.INFO, "Received result for case {0} = {1}", new Object[]{id, value});
   289                     value = decodeURL(value);
   290                     int indx = Integer.parseInt(id);
   291                     cases.get(indx).result(value, null);
   292                     if (++indx < cases.size()) {
   293                         mi = cases.get(indx);
   294                         LOG.log(Level.INFO, "Re-executing case {0}", indx);
   295                         caseNmbr = indx;
   296                     }
   297                 } else {
   298                     if (!cases.isEmpty()) {
   299                         LOG.info("Re-executing test cases");
   300                         mi = cases.get(0);
   301                         caseNmbr = 0;
   302                     }
   303                 }
   304                 
   305                 if (mi == null) {
   306                     mi = methods.take();
   307                     caseNmbr = cnt++;
   308                 }
   309                 if (mi == END) {
   310                     response.getWriter().write("");
   311                     wait.countDown();
   312                     cnt = 0;
   313                     LOG.log(Level.INFO, "End of data reached. Exiting.");
   314                     return;
   315                 }
   316                 final DynamicResourceHandler newRH = new DynamicResourceHandler(mi);
   317                 if (prev != null) {
   318                     prev.close(newRH);
   319                 }
   320                 prev = newRH;
   321                 conf.addHttpHandler(prev, "/dynamic");
   322                 
   323                 cases.add(mi);
   324                 final String cn = mi.clazz.getName();
   325                 final String mn = mi.methodName;
   326                 LOG.log(Level.INFO, "Request for {0} case. Sending {1}.{2}", new Object[]{caseNmbr, cn, mn});
   327                 response.getWriter().write("{"
   328                     + "className: '" + cn + "', "
   329                     + "methodName: '" + mn + "', "
   330                     + "request: " + caseNmbr
   331                 );
   332                 if (mi.html != null) {
   333                     response.getWriter().write(", html: '");
   334                     response.getWriter().write(encodeJSON(mi.html));
   335                     response.getWriter().write("'");
   336                 }
   337                 response.getWriter().write("}");
   338             }
   339         }, "/data");
   340 
   341         this.brwsr = launchServerAndBrwsr(server, "/execute");
   342     }
   343     
   344     private static String encodeJSON(String in) {
   345         StringBuilder sb = new StringBuilder();
   346         for (int i = 0; i < in.length(); i++) {
   347             char ch = in.charAt(i);
   348             if (ch < 32 || ch == '\'' || ch == '"') {
   349                 sb.append("\\u");
   350                 String hs = "0000" + Integer.toHexString(ch);
   351                 hs = hs.substring(hs.length() - 4);
   352                 sb.append(hs);
   353             } else {
   354                 sb.append(ch);
   355             }
   356         }
   357         return sb.toString();
   358     }
   359     
   360     @Override
   361     public void shutdown() throws IOException {
   362         methods.offer(END);
   363         for (;;) {
   364             int prev = methods.size();
   365             try {
   366                 if (wait != null && wait.await(timeOut, TimeUnit.MILLISECONDS)) {
   367                     break;
   368                 }
   369             } catch (InterruptedException ex) {
   370                 throw new IOException(ex);
   371             }
   372             if (prev == methods.size()) {
   373                 LOG.log(
   374                     Level.WARNING, 
   375                     "Timeout and no test has been executed meanwhile (at {0}). Giving up.", 
   376                     methods.size()
   377                 );
   378                 break;
   379             }
   380             LOG.log(Level.INFO, 
   381                 "Timeout, but tests got from {0} to {1}. Trying again.", 
   382                 new Object[]{prev, methods.size()}
   383             );
   384         }
   385         stopServerAndBrwsr(server, brwsr);
   386     }
   387     
   388     static void copyStream(InputStream is, OutputStream os, String baseURL, String... params) throws IOException {
   389         for (;;) {
   390             int ch = is.read();
   391             if (ch == -1) {
   392                 break;
   393             }
   394             if (ch == '$' && params.length > 0) {
   395                 int cnt = is.read() - '0';
   396                 if (baseURL != null && cnt == 'U' - '0') {
   397                     os.write(baseURL.getBytes("UTF-8"));
   398                 } else {
   399                     if (cnt >= 0 && cnt < params.length) {
   400                         os.write(params[cnt].getBytes("UTF-8"));
   401                     } else {
   402                         os.write('$');
   403                         os.write(cnt + '0');
   404                     }
   405                 }
   406             } else {
   407                 os.write(ch);
   408             }
   409         }
   410     }
   411 
   412     private Object[] launchServerAndBrwsr(HttpServer server, final String page) throws IOException, URISyntaxException, InterruptedException {
   413         server.start();
   414         URI uri = pageURL(server, page);
   415         return showBrwsr(uri);
   416     }
   417     private static String toUTF8(String value) throws UnsupportedEncodingException {
   418         byte[] arr = new byte[value.length()];
   419         for (int i = 0; i < arr.length; i++) {
   420             arr[i] = (byte)value.charAt(i);
   421         }
   422         return new String(arr, "UTF-8");
   423     }
   424     
   425     private static String decodeURL(String s) {
   426         for (;;) {
   427             int pos = s.indexOf('%');
   428             if (pos == -1) {
   429                 return s;
   430             }
   431             int i = Integer.parseInt(s.substring(pos + 1, pos + 2), 16);
   432             s = s.substring(0, pos) + (char)i + s.substring(pos + 2);
   433         }
   434     }
   435     
   436     private void stopServerAndBrwsr(HttpServer server, Object[] brwsr) throws IOException {
   437         if (brwsr == null) {
   438             return;
   439         }
   440         Process process = (Process)brwsr[0];
   441         
   442         server.stop();
   443         InputStream stdout = process.getInputStream();
   444         InputStream stderr = process.getErrorStream();
   445         drain("StdOut", stdout);
   446         drain("StdErr", stderr);
   447         process.destroy();
   448         int res;
   449         try {
   450             res = process.waitFor();
   451         } catch (InterruptedException ex) {
   452             throw new IOException(ex);
   453         }
   454         LOG.log(Level.INFO, "Exit code: {0}", res);
   455 
   456         deleteTree((File)brwsr[1]);
   457     }
   458     
   459     private static void drain(String name, InputStream is) throws IOException {
   460         int av = is.available();
   461         if (av > 0) {
   462             StringBuilder sb = new StringBuilder();
   463             sb.append("v== ").append(name).append(" ==v\n");
   464             while (av-- > 0) {
   465                 sb.append((char)is.read());
   466             }
   467             sb.append("\n^== ").append(name).append(" ==^");
   468             LOG.log(Level.INFO, sb.toString());
   469         }
   470     }
   471 
   472     private void deleteTree(File file) {
   473         if (file == null) {
   474             return;
   475         }
   476         File[] arr = file.listFiles();
   477         if (arr != null) {
   478             for (File s : arr) {
   479                 deleteTree(s);
   480             }
   481         }
   482         file.delete();
   483     }
   484 
   485     @Override
   486     public HttpServer call() throws Exception {
   487         return server;
   488     }
   489     
   490     @Override
   491     public void close() throws IOException {
   492         shutdown();
   493     }
   494 
   495     protected Object[] showBrwsr(URI uri) throws IOException {
   496         LOG.log(Level.INFO, "Showing {0}", uri);
   497         if (cmd == null) {
   498             try {
   499                 LOG.log(Level.INFO, "Trying Desktop.browse on {0} {2} by {1}", new Object[] {
   500                     System.getProperty("java.vm.name"),
   501                     System.getProperty("java.vm.vendor"),
   502                     System.getProperty("java.vm.version"),
   503                 });
   504                 java.awt.Desktop.getDesktop().browse(uri);
   505                 LOG.log(Level.INFO, "Desktop.browse successfully finished");
   506                 return null;
   507             } catch (UnsupportedOperationException ex) {
   508                 LOG.log(Level.INFO, "Desktop.browse not supported: {0}", ex.getMessage());
   509                 LOG.log(Level.FINE, null, ex);
   510             }
   511         }
   512         {
   513             String cmdName = cmd == null ? "xdg-open" : cmd;
   514             String[] cmdArr = { 
   515                 cmdName, uri.toString()
   516             };
   517             LOG.log(Level.INFO, "Launching {0}", Arrays.toString(cmdArr));
   518             final Process process = Runtime.getRuntime().exec(cmdArr);
   519             return new Object[] { process, null };
   520         }
   521     }
   522 
   523     abstract void generateBck2BrwsrJS(StringBuilder sb, Res loader) throws IOException;
   524     abstract String harnessResource();
   525 
   526     private static URI pageURL(HttpServer server, final String page) {
   527         NetworkListener listener = server.getListeners().iterator().next();
   528         int port = listener.getPort();
   529         try {
   530             return new URI("http://localhost:" + port + page);
   531         } catch (URISyntaxException ex) {
   532             throw new IllegalStateException(ex);
   533         }
   534     }
   535 
   536     class Res {
   537         public InputStream get(String resource) throws IOException {
   538             URL u = null;
   539             for (ClassLoader l : loaders) {
   540                 Enumeration<URL> en = l.getResources(resource);
   541                 while (en.hasMoreElements()) {
   542                     u = en.nextElement();
   543                     if (u.toExternalForm().matches("^.*emul.*rt\\.jar.*$")) {
   544                         return u.openStream();
   545                     }
   546                 }
   547             }
   548             if (u != null) {
   549                 if (u.toExternalForm().contains("rt.jar")) {
   550                     LOG.log(Level.WARNING, "Fallback to bootclasspath for {0}", u);
   551                 }
   552                 return u.openStream();
   553             }
   554             throw new IOException("Can't find " + resource);
   555         }
   556     }
   557 
   558     private static class Page extends HttpHandler {
   559         final String resource;
   560         private final String[] args;
   561         private final Res res;
   562         
   563         public Page(Res res, String resource, String... args) {
   564             this.res = res;
   565             this.resource = resource;
   566             this.args = args.length == 0 ? new String[] { "$0" } : args;
   567         }
   568 
   569         @Override
   570         public void service(Request request, Response response) throws Exception {
   571             String r = computePage(request);
   572             if (r.startsWith("/")) {
   573                 r = r.substring(1);
   574             }
   575             String[] replace = {};
   576             if (r.endsWith(".html")) {
   577                 response.setContentType("text/html");
   578                 LOG.info("Content type text/html");
   579                 replace = args;
   580             }
   581             if (r.endsWith(".xhtml")) {
   582                 response.setContentType("application/xhtml+xml");
   583                 LOG.info("Content type application/xhtml+xml");
   584                 replace = args;
   585             }
   586             OutputStream os = response.getOutputStream();
   587             try { 
   588                 InputStream is = res.get(r);
   589                 copyStream(is, os, request.getRequestURL().toString(), replace);
   590             } catch (IOException ex) {
   591                 response.setDetailMessage(ex.getLocalizedMessage());
   592                 response.setError();
   593                 response.setStatus(404);
   594             }
   595         }
   596 
   597         protected String computePage(Request request) {
   598             String r = resource;
   599             if (r == null) {
   600                 r = request.getHttpHandlerPath();
   601             }
   602             return r;
   603         }
   604     }
   605     
   606     private static class SubTree extends Page {
   607 
   608         public SubTree(Res res, String resource, String... args) {
   609             super(res, resource, args);
   610         }
   611 
   612         @Override
   613         protected String computePage(Request request) {
   614             return resource + request.getHttpHandlerPath();
   615         }
   616         
   617         
   618     }
   619 
   620     private class VM extends HttpHandler {
   621         @Override
   622         public void service(Request request, Response response) throws Exception {
   623             response.setCharacterEncoding("UTF-8");
   624             response.setContentType("text/javascript");
   625             StringBuilder sb = new StringBuilder();
   626             generateBck2BrwsrJS(sb, BaseHTTPLauncher.this.resources);
   627             response.getWriter().write(sb.toString());
   628         }
   629     }
   630 
   631     private static class Classes extends HttpHandler {
   632         private final Res loader;
   633 
   634         public Classes(Res loader) {
   635             this.loader = loader;
   636         }
   637 
   638         @Override
   639         public void service(Request request, Response response) throws Exception {
   640             String res = request.getHttpHandlerPath();
   641             if (res.startsWith("/")) {
   642                 res = res.substring(1);
   643             }
   644             InputStream is = null;
   645             try {
   646                 is = loader.get(res);
   647                 response.setContentType("text/javascript");
   648                 Writer w = response.getWriter();
   649                 w.append("[");
   650                 for (int i = 0;; i++) {
   651                     int b = is.read();
   652                     if (b == -1) {
   653                         break;
   654                     }
   655                     if (i > 0) {
   656                         w.append(", ");
   657                     }
   658                     if (i % 20 == 0) {
   659                         w.write("\n");
   660                     }
   661                     if (b > 127) {
   662                         b = b - 256;
   663                     }
   664                     w.append(Integer.toString(b));
   665                 }
   666                 w.append("\n]");
   667             } catch (IOException ex) {
   668                 response.setStatus(HttpStatus.NOT_FOUND_404);
   669                 response.setError();
   670                 response.setDetailMessage(ex.getMessage());
   671             } finally {
   672                 if (is != null) {
   673                     is.close();
   674                 }
   675             }
   676         }
   677     }
   678 }