rt/aot/src/main/java/org/apidesign/bck2brwsr/aot/Bck2BrwsrJars.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 23 Nov 2014 21:59:21 +0100
changeset 1728 1d850aa501bb
parent 1724 50ad005d1597
child 1729 384468666b2d
permissions -rw-r--r--
Recognizes NetBeans manifest tags
jaroslav@1599
     1
/**
jaroslav@1599
     2
 * Back 2 Browser Bytecode Translator
jaroslav@1599
     3
 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@1599
     4
 *
jaroslav@1599
     5
 * This program is free software: you can redistribute it and/or modify
jaroslav@1599
     6
 * it under the terms of the GNU General Public License as published by
jaroslav@1599
     7
 * the Free Software Foundation, version 2 of the License.
jaroslav@1599
     8
 *
jaroslav@1599
     9
 * This program is distributed in the hope that it will be useful,
jaroslav@1599
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@1599
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@1599
    12
 * GNU General Public License for more details.
jaroslav@1599
    13
 *
jaroslav@1599
    14
 * You should have received a copy of the GNU General Public License
jaroslav@1599
    15
 * along with this program. Look for COPYING file in the top folder.
jaroslav@1599
    16
 * If not, see http://opensource.org/licenses/GPL-2.0.
jaroslav@1599
    17
 */
jaroslav@1599
    18
package org.apidesign.bck2brwsr.aot;
jaroslav@1599
    19
jaroslav@1599
    20
import java.io.BufferedReader;
jaroslav@1684
    21
import java.io.ByteArrayInputStream;
jaroslav@1599
    22
import java.io.File;
jaroslav@1679
    23
import java.io.FileInputStream;
jaroslav@1599
    24
import java.io.IOException;
jaroslav@1599
    25
import java.io.InputStream;
jaroslav@1599
    26
import java.io.InputStreamReader;
jaroslav@1599
    27
import java.net.URL;
jaroslav@1599
    28
import java.util.ArrayList;
jaroslav@1599
    29
import java.util.Enumeration;
jaroslav@1678
    30
import java.util.HashMap;
jaroslav@1599
    31
import java.util.HashSet;
jaroslav@1599
    32
import java.util.List;
jaroslav@1678
    33
import java.util.Map;
jaroslav@1599
    34
import java.util.Set;
jaroslav@1724
    35
import java.util.jar.Attributes;
jaroslav@1599
    36
import java.util.jar.JarEntry;
jaroslav@1599
    37
import java.util.jar.JarFile;
jaroslav@1599
    38
import java.util.logging.Level;
jaroslav@1599
    39
import java.util.logging.Logger;
jaroslav@1599
    40
import java.util.zip.ZipEntry;
jaroslav@1599
    41
import org.apidesign.vm4brwsr.Bck2Brwsr;
jaroslav@1599
    42
jaroslav@1599
    43
/** Utilities to process JAR files and set a compiler
jaroslav@1603
    44
 * up.
jaroslav@1599
    45
 *
jaroslav@1603
    46
 * @since 0.9
jaroslav@1599
    47
 * @author Jaroslav Tulach
jaroslav@1599
    48
 */
jaroslav@1599
    49
public final class Bck2BrwsrJars {
jaroslav@1599
    50
    private static final Logger LOG = Logger.getLogger(Bck2BrwsrJars.class.getName());
jaroslav@1679
    51
jaroslav@1599
    52
    private Bck2BrwsrJars() {
jaroslav@1599
    53
    }
jaroslav@1599
    54
    
jaroslav@1599
    55
    /** Creates new compiler pre-configured from the content of 
jaroslav@1599
    56
     * provided JAR file. The compiler will compile all classes.
jaroslav@1599
    57
     * The system understands OSGi manifest entries and will export
jaroslav@1599
    58
     * all packages that are exported in the JAR file. The system
jaroslav@1628
    59
     * also recognizes META-INF/services and makes sure the class names
jaroslav@1599
    60
     * are not mangled.
jaroslav@1599
    61
     * 
jaroslav@1599
    62
     * @param c the compiler to {@link Bck2Brwsr#addClasses(java.lang.String...) add classes},
jaroslav@1599
    63
     *    {@link Bck2Brwsr#addResources(java.lang.String...) add resources} and
jaroslav@1599
    64
     *    {@link Bck2Brwsr#addExported(java.lang.String...) exported objects} to.
jaroslav@1599
    65
     *    Can be <code>null</code> - in such case an 
jaroslav@1599
    66
     *    {@link Bck2Brwsr#newCompiler() empty compiler} is constructed.
jaroslav@1599
    67
     * @param jar the file to process
jaroslav@1599
    68
     * @return newly configured compiler
jaroslav@1599
    69
     * @throws IOException if something goes wrong
jaroslav@1599
    70
     */
jaroslav@1599
    71
    public static Bck2Brwsr configureFrom(Bck2Brwsr c, File jar) throws IOException {
jaroslav@1710
    72
        return configureFrom(c, jar, null);
jaroslav@1710
    73
    }
jaroslav@1710
    74
    
jaroslav@1710
    75
    /** Creates new compiler pre-configured from the content of 
jaroslav@1710
    76
     * provided JAR file. The compiler will compile all classes.
jaroslav@1710
    77
     * The system understands OSGi manifest entries and will export
jaroslav@1710
    78
     * all packages that are exported in the JAR file. The system
jaroslav@1710
    79
     * also recognizes META-INF/services and makes sure the class names
jaroslav@1710
    80
     * are not mangled.
jaroslav@1710
    81
     * 
jaroslav@1710
    82
     * @param c the compiler to {@link Bck2Brwsr#addClasses(java.lang.String...) add classes},
jaroslav@1710
    83
     *    {@link Bck2Brwsr#addResources(java.lang.String...) add resources} and
jaroslav@1710
    84
     *    {@link Bck2Brwsr#addExported(java.lang.String...) exported objects} to.
jaroslav@1710
    85
     *    Can be <code>null</code> - in such case an 
jaroslav@1710
    86
     *    {@link Bck2Brwsr#newCompiler() empty compiler} is constructed.
jaroslav@1710
    87
     * @param jar the file to process
jaroslav@1710
    88
     * @param classpath additional resources to make available during
jaroslav@1710
    89
     *   compilation, but not include them in the generated JavaScript
jaroslav@1710
    90
     * @return newly configured compiler
jaroslav@1710
    91
     * @throws IOException if something goes wrong
jaroslav@1710
    92
     * @since 0.11
jaroslav@1710
    93
     */
jaroslav@1710
    94
    public static Bck2Brwsr configureFrom(
jaroslav@1710
    95
        Bck2Brwsr c, File jar, final ClassLoader classpath
jaroslav@1710
    96
    ) throws IOException {
jaroslav@1679
    97
        if (jar.isDirectory()) {
jaroslav@1710
    98
            return configureDir(c, jar, classpath);
jaroslav@1679
    99
        }
jaroslav@1601
   100
        final JarFile jf = new JarFile(jar);
jaroslav@1678
   101
        final List<String> classes = new ArrayList<>();
jaroslav@1601
   102
        List<String> resources = new ArrayList<>();
jaroslav@1601
   103
        Set<String> exported = new HashSet<>();
jaroslav@1601
   104
        class JarRes extends EmulationResources implements Bck2Brwsr.Resources {
jaroslav@1678
   105
            JarRes() {
jaroslav@1710
   106
                super(classpath, classes);
jaroslav@1678
   107
            }
jaroslav@1601
   108
            @Override
jaroslav@1601
   109
            public InputStream get(String resource) throws IOException {
jaroslav@1696
   110
                InputStream is = getConverted(resource);
jaroslav@1696
   111
                if (is != null) {
jaroslav@1696
   112
                    return is;
jaroslav@1696
   113
                }
jaroslav@1696
   114
                is = jf.getInputStream(new ZipEntry(resource));
jaroslav@1601
   115
                return is == null ? super.get(resource) : is;
jaroslav@1599
   116
            }
jaroslav@1599
   117
        }
jaroslav@1678
   118
        JarRes jarRes = new JarRes();
jaroslav@1678
   119
jaroslav@1678
   120
        listJAR(jf, jarRes, resources, exported);
jaroslav@1678
   121
        
jaroslav@1678
   122
        String cp = jf.getManifest().getMainAttributes().getValue("Class-Path"); // NOI18N
jaroslav@1710
   123
        String[] parts = cp == null ? new String[0] : cp.split(" ");
jaroslav@1678
   124
jaroslav@1622
   125
        if (c == null) {
jaroslav@1622
   126
            c = Bck2Brwsr.newCompiler();
jaroslav@1622
   127
        }
jaroslav@1622
   128
        
jaroslav@1622
   129
        return c
jaroslav@1710
   130
            .library(parts)
jaroslav@1601
   131
            .addClasses(classes.toArray(new String[classes.size()]))
jaroslav@1601
   132
            .addExported(exported.toArray(new String[exported.size()]))
jaroslav@1601
   133
            .addResources(resources.toArray(new String[resources.size()]))
jaroslav@1678
   134
            .resources(jarRes);
jaroslav@1599
   135
    }
jaroslav@1599
   136
    
jaroslav@1599
   137
    private static void listJAR(
jaroslav@1678
   138
        JarFile j, EmulationResources classes,
jaroslav@1599
   139
        List<String> resources, Set<String> keep
jaroslav@1599
   140
    ) throws IOException {
jaroslav@1599
   141
        Enumeration<JarEntry> en = j.entries();
jaroslav@1599
   142
        while (en.hasMoreElements()) {
jaroslav@1599
   143
            JarEntry e = en.nextElement();
jaroslav@1599
   144
            final String n = e.getName();
jaroslav@1599
   145
            if (n.endsWith("/")) {
jaroslav@1599
   146
                continue;
jaroslav@1599
   147
            }
jaroslav@1602
   148
            if (n.startsWith("META-INF/maven/")) {
jaroslav@1602
   149
                continue;
jaroslav@1602
   150
            }
jaroslav@1599
   151
            int last = n.lastIndexOf('/');
jaroslav@1599
   152
            String pkg = n.substring(0, last + 1);
jaroslav@1599
   153
            if (pkg.startsWith("java/")) {
jaroslav@1599
   154
                keep.add(pkg);
jaroslav@1599
   155
            }
jaroslav@1599
   156
            if (n.endsWith(".class")) {
jaroslav@1678
   157
                classes.addClassResource(n);
jaroslav@1599
   158
            } else {
jaroslav@1599
   159
                resources.add(n);
jaroslav@1599
   160
                if (n.startsWith("META-INF/services/") && keep != null) {
jaroslav@1599
   161
                    BufferedReader r = new BufferedReader(new InputStreamReader(j.getInputStream(e)));
jaroslav@1599
   162
                    for (;;) {
jaroslav@1599
   163
                        String l = r.readLine();
jaroslav@1599
   164
                        if (l == null) {
jaroslav@1599
   165
                            break;
jaroslav@1599
   166
                        }
jaroslav@1599
   167
                        if (l.startsWith("#")) {
jaroslav@1599
   168
                            continue;
jaroslav@1599
   169
                        }
jaroslav@1599
   170
                        keep.add(l.replace('.', '/'));
jaroslav@1599
   171
                    }
jaroslav@1599
   172
                }
jaroslav@1599
   173
            }
jaroslav@1599
   174
        }
jaroslav@1724
   175
        if (keep != null) {
jaroslav@1724
   176
            final Attributes mainAttr = j.getManifest().getMainAttributes();
jaroslav@1724
   177
            exportPublicPackages(mainAttr, keep);
jaroslav@1724
   178
        }
jaroslav@1724
   179
    }
jaroslav@1724
   180
jaroslav@1724
   181
    static void exportPublicPackages(final Attributes mainAttr, Set<String> keep) {
jaroslav@1724
   182
        String exp = mainAttr.getValue("Export-Package"); // NOI18N
jaroslav@1724
   183
        if (exp != null) {
jaroslav@1599
   184
            for (String def : exp.split(",")) {
jaroslav@1599
   185
                for (String sep : def.split(";")) {
jaroslav@1599
   186
                    keep.add(sep.replace('.', '/') + "/");
jaroslav@1599
   187
                    break;
jaroslav@1599
   188
                }
jaroslav@1599
   189
            }
jaroslav@1728
   190
            return;
jaroslav@1728
   191
        }
jaroslav@1728
   192
        exp = mainAttr.getValue("OpenIDE-Module-Public-Packages");
jaroslav@1728
   193
        if (exp != null) {
jaroslav@1728
   194
            for (String def : exp.split(",")) {
jaroslav@1728
   195
                def = def.trim();
jaroslav@1728
   196
                if (def.endsWith(".*")) {
jaroslav@1728
   197
                    keep.add(def.substring(0, def.length() - 1).replace('.', '/'));
jaroslav@1728
   198
                }
jaroslav@1728
   199
            }
jaroslav@1599
   200
        }
jaroslav@1599
   201
    }
jaroslav@1678
   202
    
jaroslav@1678
   203
    static byte[] readFrom(InputStream is) throws IOException {
jaroslav@1678
   204
        int expLen = is.available();
jaroslav@1678
   205
        if (expLen < 1) {
jaroslav@1678
   206
            expLen = 1;
jaroslav@1678
   207
        }
jaroslav@1678
   208
        byte[] arr = new byte[expLen];
jaroslav@1678
   209
        int pos = 0;
jaroslav@1678
   210
        for (;;) {
jaroslav@1678
   211
            int read = is.read(arr, pos, arr.length - pos);
jaroslav@1678
   212
            if (read == -1) {
jaroslav@1678
   213
                break;
jaroslav@1678
   214
            }
jaroslav@1678
   215
            pos += read;
jaroslav@1678
   216
            if (pos == arr.length) {
jaroslav@1678
   217
                byte[] tmp = new byte[arr.length * 2];
jaroslav@1678
   218
                System.arraycopy(arr, 0, tmp, 0, arr.length);
jaroslav@1678
   219
                arr = tmp;
jaroslav@1678
   220
            }
jaroslav@1678
   221
        }
jaroslav@1678
   222
        if (pos != arr.length) {
jaroslav@1678
   223
            byte[] tmp = new byte[pos];
jaroslav@1678
   224
            System.arraycopy(arr, 0, tmp, 0, pos);
jaroslav@1678
   225
            arr = tmp;
jaroslav@1678
   226
        }
jaroslav@1678
   227
        return arr;
jaroslav@1678
   228
    }
jaroslav@1678
   229
    
jaroslav@1599
   230
jaroslav@1599
   231
    static class EmulationResources implements Bck2Brwsr.Resources {
jaroslav@1678
   232
        private final List<String> classes;
jaroslav@1678
   233
        private final Map<String,byte[]> converted = new HashMap<>();
jaroslav@1678
   234
        private final BytecodeProcessor proc;
jaroslav@1710
   235
        private final ClassLoader cp;
jaroslav@1678
   236
jaroslav@1710
   237
        protected EmulationResources(ClassLoader cp, List<String> classes) {
jaroslav@1678
   238
            this.classes = classes;
jaroslav@1710
   239
            this.cp = cp != null ? cp : Bck2BrwsrJars.class.getClassLoader();
jaroslav@1678
   240
            BytecodeProcessor p;
jaroslav@1678
   241
            try {
jaroslav@1678
   242
                Class<?> bpClass = Class.forName("org.apidesign.bck2brwsr.aot.RetroLambda");
jaroslav@1678
   243
                p = (BytecodeProcessor) bpClass.newInstance();
jaroslav@1678
   244
            } catch (Throwable t) {
jaroslav@1678
   245
                p = null;
jaroslav@1678
   246
            }
jaroslav@1678
   247
            this.proc = p;
jaroslav@1678
   248
        }
jaroslav@1599
   249
jaroslav@1696
   250
        protected final InputStream getConverted(String name) throws IOException {
jaroslav@1684
   251
            byte[] arr = converted.get(name);
jaroslav@1684
   252
            if (arr != null) {
jaroslav@1684
   253
                return new ByteArrayInputStream(arr);
jaroslav@1684
   254
            }
jaroslav@1696
   255
            return null;
jaroslav@1696
   256
        }
jaroslav@1696
   257
        
jaroslav@1696
   258
        @Override
jaroslav@1696
   259
        public InputStream get(String name) throws IOException {
jaroslav@1696
   260
            InputStream is = getConverted(name);
jaroslav@1696
   261
            if (is != null) {
jaroslav@1696
   262
                return is;
jaroslav@1696
   263
            }
jaroslav@1710
   264
            Enumeration<URL> en = cp.getResources(name);
jaroslav@1599
   265
            URL u = null;
jaroslav@1599
   266
            while (en.hasMoreElements()) {
jaroslav@1599
   267
                u = en.nextElement();
jaroslav@1599
   268
            }
jaroslav@1599
   269
            if (u == null) {
jaroslav@1599
   270
                LOG.log(Level.WARNING, "Cannot find {0}", name);
jaroslav@1599
   271
                return null;
jaroslav@1599
   272
            }
jaroslav@1599
   273
            if (u.toExternalForm().contains("/rt.jar!")) {
jaroslav@1599
   274
                LOG.log(Level.WARNING, "{0}No bootdelegation for ", name);
jaroslav@1599
   275
                return null;
jaroslav@1599
   276
            }
jaroslav@1599
   277
            return u.openStream();
jaroslav@1599
   278
        }
jaroslav@1678
   279
jaroslav@1678
   280
        private void addClassResource(String n) throws IOException {
jaroslav@1678
   281
            if (proc != null) {
jaroslav@1678
   282
                try (InputStream is = this.get(n)) {
jaroslav@1678
   283
                    Map<String, byte[]> conv = proc.process(n, readFrom(is), this);
jaroslav@1678
   284
                    if (conv != null) {
jaroslav@1681
   285
                        boolean found = false;
jaroslav@1681
   286
                        for (Map.Entry<String, byte[]> entrySet : conv.entrySet()) {
jaroslav@1681
   287
                            String res = entrySet.getKey();
jaroslav@1681
   288
                            byte[] bytes = entrySet.getValue();
jaroslav@1681
   289
                            if (res.equals(n)) {
jaroslav@1681
   290
                                found = true;
jaroslav@1681
   291
                            }
jaroslav@1684
   292
                            assert res.endsWith(".class") : "Wrong resource: " + res;
jaroslav@1681
   293
                            converted.put(res, bytes);
jaroslav@1681
   294
                            classes.add(res.substring(0, res.length() - 6));
jaroslav@1681
   295
                        }
jaroslav@1681
   296
                        if (!found) {
jaroslav@1678
   297
                            throw new IOException("Cannot find " + n + " among " + conv);
jaroslav@1678
   298
                        }
jaroslav@1678
   299
                        return;
jaroslav@1678
   300
                    }
jaroslav@1678
   301
                }
jaroslav@1678
   302
            }
jaroslav@1678
   303
            classes.add(n.substring(0, n.length() - 6));
jaroslav@1678
   304
        }
jaroslav@1599
   305
    }
jaroslav@1599
   306
    
jaroslav@1710
   307
    private static Bck2Brwsr configureDir(Bck2Brwsr c, final File dir, ClassLoader cp) throws IOException {
jaroslav@1679
   308
        List<String> arr = new ArrayList<>();
jaroslav@1679
   309
        List<String> classes = new ArrayList<>();
jaroslav@1679
   310
        class DirRes extends EmulationResources {
jaroslav@1710
   311
            public DirRes(ClassLoader cp, List<String> classes) {
jaroslav@1710
   312
                super(cp, classes);
jaroslav@1679
   313
            }
jaroslav@1679
   314
jaroslav@1679
   315
            @Override
jaroslav@1679
   316
            public InputStream get(String name) throws IOException {
jaroslav@1679
   317
                InputStream is = super.get(name);
jaroslav@1679
   318
                if (is != null) {
jaroslav@1679
   319
                    return is;
jaroslav@1679
   320
                }
jaroslav@1679
   321
                File r = new File(dir, name.replace('/', File.separatorChar));
jaroslav@1679
   322
                if (r.exists()) {
jaroslav@1679
   323
                    return new FileInputStream(r);
jaroslav@1679
   324
                }
jaroslav@1679
   325
                return null;
jaroslav@1679
   326
            }
jaroslav@1679
   327
        }
jaroslav@1710
   328
        DirRes dirRes = new DirRes(cp, classes);
jaroslav@1679
   329
        listDir(dir, null, dirRes, arr);
jaroslav@1679
   330
        if (c == null) {
jaroslav@1679
   331
            c = Bck2Brwsr.newCompiler();
jaroslav@1679
   332
        }
jaroslav@1679
   333
        return c
jaroslav@1679
   334
        .addRootClasses(classes.toArray(new String[0]))
jaroslav@1679
   335
        .addResources(arr.toArray(new String[0]))
jaroslav@1679
   336
        .library()
jaroslav@1679
   337
        //.obfuscation(ObfuscationLevel.FULL)
jaroslav@1679
   338
        .resources(dirRes);
jaroslav@1679
   339
    }
jaroslav@1679
   340
jaroslav@1679
   341
    private static void listDir(
jaroslav@1679
   342
        File f, String pref, EmulationResources res, List<String> resources
jaroslav@1679
   343
    ) throws IOException {
jaroslav@1679
   344
        File[] arr = f.listFiles();
jaroslav@1679
   345
        if (arr == null) {
jaroslav@1679
   346
            if (f.getName().endsWith(".class")) {
jaroslav@1679
   347
                res.addClassResource(pref + f.getName());
jaroslav@1679
   348
            } else {
jaroslav@1679
   349
                resources.add(pref + f.getName());
jaroslav@1679
   350
            }
jaroslav@1679
   351
        } else {
jaroslav@1679
   352
            for (File ch : arr) {
jaroslav@1679
   353
                listDir(ch, pref == null ? "" : pref + f.getName() + "/", res, resources);
jaroslav@1679
   354
            }
jaroslav@1679
   355
        }
jaroslav@1679
   356
    }
jaroslav@1678
   357
    
jaroslav@1599
   358
}