rt/mojo/src/main/java/org/apidesign/bck2brwsr/mojo/AheadOfTime.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 09 Jan 2015 20:46:35 +0100
changeset 1762 293838e72201
parent 1737 82fd3830167d
child 1769 f6057dc5922c
permissions -rw-r--r--
Always write down the JavaScript file in UTF-8 encoding
     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 
    19 package org.apidesign.bck2brwsr.mojo;
    20 
    21 import java.io.File;
    22 import java.io.FileOutputStream;
    23 import java.io.IOException;
    24 import java.io.InputStream;
    25 import java.io.OutputStreamWriter;
    26 import java.io.Writer;
    27 import java.net.MalformedURLException;
    28 import java.net.URL;
    29 import java.net.URLClassLoader;
    30 import java.nio.file.Files;
    31 import java.util.ArrayList;
    32 import java.util.Collection;
    33 import java.util.List;
    34 import java.util.Map;
    35 import java.util.jar.Attributes;
    36 import java.util.jar.JarFile;
    37 import java.util.jar.Manifest;
    38 import java.util.zip.ZipEntry;
    39 import org.apache.maven.artifact.Artifact;
    40 import org.apache.maven.plugin.AbstractMojo;
    41 import org.apache.maven.plugin.MojoExecutionException;
    42 import org.apache.maven.plugin.MojoFailureException;
    43 import org.apache.maven.plugins.annotations.LifecyclePhase;
    44 import org.apache.maven.plugins.annotations.Mojo;
    45 import org.apache.maven.plugins.annotations.Parameter;
    46 import org.apache.maven.plugins.annotations.ResolutionScope;
    47 import org.apache.maven.project.MavenProject;
    48 import org.apidesign.bck2brwsr.aot.Bck2BrwsrJars;
    49 import org.apidesign.vm4brwsr.Bck2Brwsr;
    50 import org.apidesign.vm4brwsr.ObfuscationLevel;
    51 
    52 /**
    53  *
    54  * @author Jaroslav Tulach
    55  * @since 0.9
    56  */
    57 @Mojo(name = "aot",
    58     requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
    59     defaultPhase = LifecyclePhase.PACKAGE
    60 )
    61 public class AheadOfTime extends AbstractMojo {
    62     @Parameter(defaultValue = "${project}")
    63     private MavenProject prj;
    64     
    65     @Parameter(defaultValue = "${project.build.directory}/${project.build.finalName}.jar")
    66     private File mainJar;
    67 
    68     @Parameter(defaultValue = "${project.build.directory}/${project.build.finalName}.js")
    69     private File mainJavaScript;
    70     
    71     @Parameter
    72     private String[] exports;
    73     
    74     /**
    75      * Directory where to generate ahead-of-time JavaScript files for
    76      * required libraries.
    77      */
    78     @Parameter(defaultValue = "lib")
    79     private String classPathPrefix;
    80 
    81     /** Root JavaScript file to generate */
    82     @Parameter(defaultValue="${project.build.directory}/bck2brwsr.js")
    83     private File vm;
    84     
    85     @Parameter(defaultValue = "true")
    86     private boolean generateAotLibraries;
    87     
    88     /**
    89      * The obfuscation level for the generated JavaScript file.
    90      *
    91      * @since 0.5
    92      */
    93     @Parameter(defaultValue = "NONE")
    94     private ObfuscationLevel obfuscation;
    95     
    96     @Override
    97     public void execute() throws MojoExecutionException, MojoFailureException {
    98         URLClassLoader loader;
    99         try {
   100             loader = buildClassLoader(mainJar, prj.getArtifacts());
   101         } catch (MalformedURLException ex) {
   102             throw new MojoFailureException("Can't initialize classloader");
   103         }
   104         for (Artifact a : prj.getArtifacts()) {
   105             if (a.getFile() == null) {
   106                 continue;
   107             }
   108             String n = a.getFile().getName();
   109             if (!n.endsWith(".jar")) {
   110                 continue;
   111             }
   112             if ("provided".equals(a.getScope())) {
   113                 continue;
   114             }
   115             File aot = new File(prj.getBuild().getDirectory(), classPathPrefix);
   116             aot.mkdirs();
   117             File js = new File(aot, n.substring(0, n.length() - 4) + ".js");
   118             if (js.exists()) {
   119                 getLog().info("Skipping " + js + " as it already exists.");
   120                 continue;
   121             }
   122             try {
   123                 aotLibrary(a, js , loader);
   124             } catch (IOException ex) {
   125                 throw new MojoFailureException("Can't compile " + a.getFile(), ex);
   126             }
   127         }
   128         
   129         try {
   130             if (mainJavaScript.exists()) {
   131                 getLog().info("Skipping " + mainJavaScript + " as it already exists.");
   132             } else {
   133                 getLog().info("Generating " + mainJavaScript);
   134                 Bck2Brwsr c = Bck2BrwsrJars.configureFrom(null, mainJar, loader);
   135                 if (exports != null) {
   136                     for (String e : exports) {
   137                         c = c.addExported(e.replace('.', '/'));
   138                     }
   139                 }
   140                 Writer w = new OutputStreamWriter(new FileOutputStream(mainJavaScript), "UTF-8");
   141                 c.
   142                         obfuscation(obfuscation).
   143                         generate(w);
   144                 w.close();
   145             }
   146         } catch (IOException ex) {
   147             throw new MojoFailureException("Cannot generate script for " + mainJar, ex);
   148         }
   149             
   150         try {
   151             Writer w = new OutputStreamWriter(new FileOutputStream(vm), "UTF-8");
   152             Bck2Brwsr.newCompiler().
   153                     obfuscation(obfuscation).
   154                     standalone(false).
   155                     resources(new Bck2Brwsr.Resources() {
   156 
   157                 @Override
   158                 public InputStream get(String resource) throws IOException {
   159                     return null;
   160                 }
   161             }).
   162                     generate(w);
   163             w.close();
   164             
   165         } catch (IOException ex) {
   166             throw new MojoExecutionException("Can't compile", ex);
   167         }
   168     }
   169 
   170     private void aotLibrary(Artifact a, File js, URLClassLoader loader) throws IOException, MojoExecutionException {
   171         for (Artifact b : prj.getArtifacts()) {
   172             if ("bck2brwsr".equals(b.getClassifier())) { // NOI18N
   173                 getLog().debug("Inspecting " + b.getFile());
   174                 JarFile jf = new JarFile(b.getFile());
   175                 Manifest man = jf.getManifest();
   176                 for (Map.Entry<String, Attributes> entrySet : man.getEntries().entrySet()) {
   177                     String entryName = entrySet.getKey();
   178                     Attributes attr = entrySet.getValue();
   179                     
   180                     if (
   181                         a.getArtifactId().equals(attr.getValue("Bck2BrwsrArtifactId")) &&
   182                         a.getGroupId().equals(attr.getValue("Bck2BrwsrGroupId")) &&
   183                         a.getVersion().equals(attr.getValue("Bck2BrwsrVersion")) &&
   184                         (
   185                             obfuscation == ObfuscationLevel.FULL && "true".equals(attr.getValue("Bck2BrwsrMinified"))
   186                             ||
   187                             obfuscation != ObfuscationLevel.FULL && "true".equals(attr.getValue("Bck2BrwsrDebug"))
   188                         )
   189                     ) {
   190                         getLog().info("Extracting " + js + " from " + b.getFile());
   191                         InputStream is = jf.getInputStream(new ZipEntry(entryName));
   192                         Files.copy(is, js.toPath());
   193                         is.close();
   194                         return;
   195                     }
   196                 }
   197             }
   198         }
   199         if (!generateAotLibraries) {
   200             throw new MojoExecutionException("Not generating " + js + " and no precompiled version found!");
   201         }
   202         getLog().info("Generating " + js);
   203         Writer w = new OutputStreamWriter(new FileOutputStream(js), "UTF-8");
   204         Bck2Brwsr c = Bck2BrwsrJars.configureFrom(null, a.getFile(), loader);
   205         c.
   206             obfuscation(obfuscation).
   207             generate(w);
   208         w.close();
   209     }
   210     private static URLClassLoader buildClassLoader(File root, Collection<Artifact> deps) throws MalformedURLException {
   211         List<URL> arr = new ArrayList<URL>();
   212         if (root != null) {
   213             arr.add(root.toURI().toURL());
   214         }
   215         for (Artifact a : deps) {
   216             if (a.getFile() != null) {
   217                 arr.add(a.getFile().toURI().toURL());
   218             }
   219         }
   220         return new URLClassLoader(arr.toArray(new URL[0]), Java2JavaScript.class.getClassLoader());
   221     }
   222 }