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