launcher/http/src/main/java/org/apidesign/bck2brwsr/launcher/CompileCP.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 05 May 2014 08:36:50 +0200
branchclosure
changeset 1523 d1eeb43a75a3
parent 1517 7f11e94f413d
child 1525 777bd3ed81ba
permissions -rw-r--r--
More robust against missing classes
     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.File;
    21 import java.io.IOException;
    22 import java.io.InputStream;
    23 import java.io.StringWriter;
    24 import java.net.JarURLConnection;
    25 import java.net.URISyntaxException;
    26 import java.net.URL;
    27 import java.util.ArrayList;
    28 import java.util.Enumeration;
    29 import java.util.List;
    30 import java.util.jar.JarEntry;
    31 import java.util.jar.JarFile;
    32 import java.util.logging.Level;
    33 import java.util.logging.Logger;
    34 import java.util.zip.ZipEntry;
    35 import org.apidesign.bck2brwsr.launcher.BaseHTTPLauncher.Res;
    36 import org.apidesign.vm4brwsr.Bck2Brwsr;
    37 
    38 /**
    39  *
    40  * @author Jaroslav Tulach
    41  */
    42 class CompileCP {
    43     private static final Logger LOG = Logger.getLogger(CompileCP.class.getName());
    44     static String compileJAR(final JarFile jar) throws IOException {
    45         List<String> arr = new ArrayList<>();
    46         List<String> classes = new ArrayList<>();
    47         listJAR(jar, classes, arr);
    48         StringWriter w = new StringWriter();
    49         try {
    50             class JarRes extends EmulationResources implements Bck2Brwsr.Resources {
    51                 @Override
    52                 public InputStream get(String resource) throws IOException {
    53                     InputStream is = jar.getInputStream(new ZipEntry(resource));
    54                     return is == null ? super.get(resource) : is;
    55                 }
    56             }
    57             
    58             Bck2Brwsr.newCompiler()
    59                 .addClasses(classes.toArray(new String[0]))
    60                 .addResources(arr.toArray(new String[0]))
    61                 .library(true)
    62                 .resources(new JarRes())
    63                 .generate(w);
    64             w.flush();
    65             return w.toString();
    66         } catch (IOException ex) {
    67             throw ex;
    68         } catch (Throwable ex) {
    69             throw new IOException("Cannot compile: ", ex);
    70         } finally {
    71             w.close();
    72         }
    73     }
    74     
    75     static String compileFromClassPath(URL u, final Res r) throws IOException {
    76         File f;
    77         try {
    78             f = new File(u.toURI());
    79         } catch (URISyntaxException ex) {
    80             throw new IOException(ex);
    81         }
    82         for (String s : System.getProperty("java.class.path").split(File.pathSeparator)) {
    83             if (!f.getPath().startsWith(s)) {
    84                 continue;
    85             }
    86             File root = new File(s);
    87             List<String> arr = new ArrayList<>();
    88             List<String> classes = new ArrayList<>();
    89             listDir(root, null, classes, arr);
    90             StringWriter w = new StringWriter();
    91             try {
    92                 Bck2Brwsr.newCompiler()
    93                     .addRootClasses(classes.toArray(new String[0]))
    94                     .addResources(arr.toArray(new String[0]))
    95                     .library(true)
    96                     .resources(new EmulationResources() {
    97                         @Override
    98                         public InputStream get(String resource) throws IOException {
    99                             if (r != null) {
   100                                 final URL url = r.get(resource, 0);
   101                                 return url == null ? null : url.openStream();
   102                             }
   103                             return super.get(resource);
   104                         }
   105                     })
   106                     .generate(w);
   107                 w.flush();
   108                 return w.toString();
   109             } catch (ClassFormatError ex) {
   110                 throw new IOException(ex);
   111             } finally {
   112                 w.close();
   113             }
   114         }
   115         return null;
   116     }
   117     
   118     private static void listJAR(JarFile j, List<String> classes, List<String> resources) throws IOException {
   119         Enumeration<JarEntry> en = j.entries();
   120         while (en.hasMoreElements()) {
   121             JarEntry e = en.nextElement();
   122             final String n = e.getName();
   123             if (n.contains("package-info")) {
   124                 continue;
   125             }
   126             if (n.endsWith("/")) {
   127                 continue;
   128             }
   129             int last = n.lastIndexOf('/');
   130             String pkg = n.substring(0, last + 1);
   131             if (skipPkg(pkg)) {
   132                 continue;
   133             }
   134             if (n.endsWith(".class")) {
   135                 classes.add(n.substring(0, n.length() - 6));
   136             } else {
   137                 resources.add(n);
   138             }
   139         }
   140     }
   141 
   142     private static boolean skipPkg(String pkg) {
   143         return pkg.equals("org/apidesign/bck2brwsr/launcher/");
   144     }
   145     
   146     private static void listDir(File f, String pref, List<String> classes, List<String> resources) throws IOException {
   147         File[] arr = f.listFiles();
   148         if (arr == null) {
   149             if (f.getName().equals("package-info.class")) {
   150                 return;
   151             }
   152             if (f.getName().endsWith(".class")) {
   153                 classes.add(pref + f.getName().substring(0, f.getName().length() - 6));
   154             } else {
   155                 resources.add(pref + f.getName());
   156             }
   157         } else {
   158             for (File ch : arr) {
   159                 
   160                 listDir(ch, pref == null ? "" : pref + f.getName() + "/", classes, resources);
   161             }
   162         }
   163     }
   164 
   165     static void compileVM(StringBuilder sb, final Res r) throws IOException {
   166         URL u = r.get(InterruptedException.class.getName().replace('.', '/') + ".class", 0);
   167         JarURLConnection juc = (JarURLConnection)u.openConnection();
   168         
   169         List<String> arr = new ArrayList<>();
   170         List<String> classes = new ArrayList<>();
   171         listJAR(juc.getJarFile(), classes, arr);
   172 
   173         Bck2Brwsr.newCompiler().addRootClasses(classes.toArray(new String[0]))
   174             .resources(new Bck2Brwsr.Resources() {
   175                 @Override
   176                 public InputStream get(String resource) throws IOException {
   177                     final URL url = r.get(resource, 0);
   178                     return url == null ? null : url.openStream();
   179                 }
   180             }).generate(sb);
   181     }
   182 
   183     static class EmulationResources implements Bck2Brwsr.Resources {
   184 
   185         @Override
   186         public InputStream get(String name) throws IOException {
   187             Enumeration<URL> en = CompileCP.class.getClassLoader().getResources(name);
   188             URL u = null;
   189             while (en.hasMoreElements()) {
   190                 u = en.nextElement();
   191             }
   192             if (u == null) {
   193                 LOG.log(Level.WARNING, "Cannot find {0}", name);
   194                 return null;
   195             }
   196             if (u.toExternalForm().contains("/rt.jar!")) {
   197                 LOG.warning(name + "No bootdelegation for ");
   198                 return null;
   199             }
   200             return u.openStream();
   201         }
   202     }
   203 }