rt/vm/src/main/java/org/apidesign/vm4brwsr/Main.java
author Lubomir Nerad <lubomir.nerad@oracle.com>
Thu, 25 Apr 2013 16:17:48 +0200
branchclosure
changeset 1020 a6bacea2518f
parent 881 6a3a063b6eb1
child 1029 b1fe994d4267
permissions -rw-r--r--
Initial structure for extension modules
     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.vm4brwsr;
    19 
    20 import java.io.BufferedWriter;
    21 import java.io.File;
    22 import java.io.FileWriter;
    23 import java.io.IOException;
    24 import java.io.Writer;
    25 import java.net.URI;
    26 import java.net.URISyntaxException;
    27 import java.net.URL;
    28 import java.util.Enumeration;
    29 import java.util.jar.JarEntry;
    30 import java.util.jar.JarFile;
    31 
    32 /** Generator of JavaScript from bytecode of classes on classpath of the VM
    33  * with a Main method.
    34  *
    35  * @author Jaroslav Tulach <jtulach@netbeans.org>
    36  */
    37 final class Main {
    38     private Main() {}
    39     
    40     public static void main(String... args) throws IOException, URISyntaxException {
    41         final String obfuscate = "--obfuscatelevel";
    42         
    43         if (args.length < 2) {
    44             System.err.println("Bck2Brwsr Translator from Java(tm) to JavaScript, (c) Jaroslav Tulach 2012");
    45             System.err.println("Usage: java -cp ... -jar ... [");
    46             System.err.print(obfuscate);
    47             System.err.print(" [");
    48             boolean first = true;
    49             for (ObfuscationLevel l : ObfuscationLevel.values()) {
    50                 if (!first) {
    51                     System.err.print('|');
    52                 }
    53                 System.err.print(l.name());
    54                 first = false;
    55             }
    56                 
    57             System.err.println("] <file_to_generate_js_code_to> java/lang/Class org/your/App ...");
    58             System.exit(9);
    59         }
    60 
    61         final ClassLoader mainClassLoader = Main.class.getClassLoader();
    62 
    63         ObfuscationLevel obfLevel = ObfuscationLevel.NONE;
    64         StringArray classes = new StringArray();
    65         String generateTo = null;
    66         for (int i = 0; i < args.length; i++) {
    67             if (obfuscate.equals(args[i])) { // NOI18N
    68                 i++;
    69                 try {
    70                     obfLevel = ObfuscationLevel.valueOf(args[i]);
    71                 } catch (Exception e) {
    72                     System.err.print(obfuscate);
    73                     System.err.print(" parameter needs to be followed by one of ");
    74                     boolean first = true;
    75                     for (ObfuscationLevel l : ObfuscationLevel.values()) {
    76                         if (!first) {
    77                             System.err.print(", ");
    78                         }
    79                         System.err.print(l.name());
    80                         first = false;
    81                     }
    82                     System.err.println();
    83                     System.exit(1);
    84                 }
    85                 continue;
    86             }
    87             if (generateTo == null) {
    88                 generateTo = args[i];
    89             } else {
    90                 collectClasses(classes, mainClassLoader, args[i]);
    91             }
    92         }
    93         try (Writer w = new BufferedWriter(new FileWriter(generateTo))) {
    94             Bck2Brwsr.newCompiler().
    95                 obfuscation(obfLevel).
    96                 addRootClasses(classes.toArray()).
    97                 resources(mainClassLoader).
    98                 generate(w);
    99         }
   100     }
   101 
   102     private static void collectClasses(
   103             final StringArray dest,
   104             final ClassLoader cl, final String relativePath)
   105                 throws IOException, URISyntaxException {
   106         final Enumeration<URL> urls = cl.getResources(relativePath);
   107         if (!urls.hasMoreElements()) {
   108             dest.add(relativePath);
   109             return;
   110         }
   111         do {
   112             final URL url = urls.nextElement();
   113             switch (url.getProtocol()) {
   114                 case "file":
   115                     collectClasses(dest, relativePath,
   116                                    new File(new URI(url.toString())));
   117                     continue;
   118                 case "jar":
   119                     final String fullPath = url.getPath();
   120                     final int sepIndex = fullPath.indexOf('!');
   121                     final String jarFilePath =
   122                             (sepIndex != -1) ? fullPath.substring(0, sepIndex)
   123                                              : fullPath;
   124 
   125                     final URI jarUri = new URI(jarFilePath);
   126                     if (jarUri.getScheme().equals("file")) {
   127                         try (JarFile jarFile = new JarFile(new File(jarUri))) {
   128                             collectClasses(dest, relativePath, jarFile);
   129                             continue;
   130                         }
   131                     }
   132                     break;
   133             }
   134 
   135             dest.add(relativePath);
   136         } while (urls.hasMoreElements());
   137     }
   138 
   139     private static void collectClasses(final StringArray dest,
   140                                        final String relativePath,
   141                                        final File file) {
   142         if (file.isDirectory()) {
   143             final File[] subFiles = file.listFiles();
   144             for (final File subFile: subFiles) {
   145                 collectClasses(dest,
   146                                extendPath(relativePath, subFile.getName()),
   147                                subFile);
   148             }
   149 
   150             return;
   151         }
   152 
   153         final String filePath = file.getPath();
   154         if (filePath.endsWith(".class")) {
   155             validateAndAddClass(dest, relativePath);
   156         }
   157     }
   158 
   159     private static void collectClasses(final StringArray dest,
   160                                        final String relativePath,
   161                                        final JarFile jarFile) {
   162         if (relativePath.endsWith(".class")) {
   163             if (jarFile.getJarEntry(relativePath) != null) {
   164                 validateAndAddClass(dest, relativePath);
   165             }
   166 
   167             return;
   168         }
   169 
   170         final String expectedPrefix =
   171                 relativePath.endsWith("/") ? relativePath
   172                                            : relativePath + '/';
   173         final Enumeration<JarEntry> entries = jarFile.entries();
   174         while (entries.hasMoreElements()) {
   175             final JarEntry entry = entries.nextElement();
   176             if (!entry.isDirectory()) {
   177                 final String entryName = entry.getName();
   178                 if (entryName.startsWith(expectedPrefix)
   179                         && entryName.endsWith(".class")) {
   180                     validateAndAddClass(dest, entryName);
   181                 }
   182             }
   183         }
   184     }
   185 
   186     private static String extendPath(final String relativePath,
   187                                      final String fileName) {
   188         return relativePath.endsWith("/") ? relativePath + fileName
   189                                           : relativePath + '/' + fileName;
   190     }
   191 
   192     private static void validateAndAddClass(final StringArray dest,
   193                                             final String relativePath) {
   194         final String className =
   195                 relativePath.substring(0, relativePath.length() - 6);
   196         if (!className.endsWith("package-info")) {
   197             dest.add(className);
   198         }
   199     }
   200 }