html4j-maven-plugin/src/main/java/org/netbeans/html/mojo/ProcessJsAnnotationsMojo.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Fri, 07 Feb 2014 07:44:34 +0100
changeset 551 7ca2253fa86d
parent 536 83deda5c6ea5
child 728 90fc6f6e508b
permissions -rw-r--r--
Updating copyright headers to mention current year
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
     5  *
     6  * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
     7  * Other names may be trademarks of their respective owners.
     8  *
     9  * The contents of this file are subject to the terms of either the GNU
    10  * General Public License Version 2 only ("GPL") or the Common
    11  * Development and Distribution License("CDDL") (collectively, the
    12  * "License"). You may not use this file except in compliance with the
    13  * License. You can obtain a copy of the License at
    14  * http://www.netbeans.org/cddl-gplv2.html
    15  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    16  * specific language governing permissions and limitations under the
    17  * License.  When distributing the software, include this License Header
    18  * Notice in each file and include the License file at
    19  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    20  * particular file as subject to the "Classpath" exception as provided
    21  * by Oracle in the GPL Version 2 section of the License file that
    22  * accompanied this code. If applicable, add the following below the
    23  * License Header, with the fields enclosed by brackets [] replaced by
    24  * your own identifying information:
    25  * "Portions Copyrighted [year] [name of copyright owner]"
    26  *
    27  * Contributor(s):
    28  *
    29  * The Original Software is NetBeans. The Initial Developer of the Original
    30  * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
    31  *
    32  * If you wish your version of this file to be governed by only the CDDL
    33  * or only the GPL Version 2, indicate your decision by adding
    34  * "[Contributor] elects to include this software in this distribution
    35  * under the [CDDL or GPL Version 2] license." If you do not indicate a
    36  * single choice of license, a recipient has the option to distribute
    37  * your version of this file under either the CDDL, the GPL Version 2 or
    38  * to extend the choice of license to its licensees as provided above.
    39  * However, if you add GPL Version 2 code and therefore, elected the GPL
    40  * Version 2 license, then the option applies only if the new code is
    41  * made subject to such option by the copyright holder.
    42  */
    43 package org.netbeans.html.mojo;
    44 
    45 import java.io.BufferedReader;
    46 import java.io.File;
    47 import java.io.FileInputStream;
    48 import java.io.FileNotFoundException;
    49 import java.io.FileOutputStream;
    50 import java.io.FileReader;
    51 import java.io.FileWriter;
    52 import java.io.IOException;
    53 import java.io.InputStream;
    54 import java.lang.reflect.Method;
    55 import java.net.MalformedURLException;
    56 import java.net.URL;
    57 import java.net.URLClassLoader;
    58 import java.util.ArrayList;
    59 import java.util.List;
    60 import org.apache.maven.artifact.Artifact;
    61 import org.apache.maven.plugin.AbstractMojo;
    62 import org.apache.maven.plugin.MojoExecutionException;
    63 import org.apache.maven.plugin.MojoFailureException;
    64 import org.apache.maven.plugins.annotations.Component;
    65 import org.apache.maven.plugins.annotations.LifecyclePhase;
    66 import org.apache.maven.plugins.annotations.Mojo;
    67 import org.apache.maven.plugins.annotations.Parameter;
    68 import org.apache.maven.plugins.annotations.ResolutionScope;
    69 import org.apache.maven.project.MavenProject;
    70 import org.objectweb.asm.ClassReader;
    71 
    72 @Mojo(
    73     name="process-js-annotations",
    74     requiresDependencyResolution = ResolutionScope.COMPILE,
    75     defaultPhase= LifecyclePhase.PROCESS_CLASSES
    76 )
    77 public final class ProcessJsAnnotationsMojo extends AbstractMojo {
    78     @Component
    79     private MavenProject prj;
    80     
    81     @Parameter(defaultValue = "${project.build.directory}/classes")
    82     private File classes;
    83     
    84     public ProcessJsAnnotationsMojo() {
    85     }
    86 
    87     @Override
    88     public void execute() throws MojoExecutionException, MojoFailureException {
    89         List<URL> arr = new ArrayList<URL>();
    90         boolean foundAsm = false;
    91         for (Artifact a : prj.getArtifacts()) {
    92             final File f = a.getFile();
    93             if (f != null) {
    94                 if (a.getArtifactId().equals("asm")) {
    95                     foundAsm = true;
    96                 }
    97                 try {
    98                     arr.add(f.toURI().toURL());
    99                 } catch (MalformedURLException ex) {
   100                     throw new IllegalStateException(ex);
   101                 }
   102             }
   103         }
   104         if (!foundAsm) {
   105             URL loc = ClassReader.class.getProtectionDomain().getCodeSource().getLocation();
   106             arr.add(loc);
   107         }
   108         URLClassLoader l = new URLClassLoader(arr.toArray(new URL[arr.size()]));
   109         try {
   110             File master = new File(new File(classes, "META-INF"), "net.java.html.js.classes");
   111             processClasses(l, master, classes);
   112         } catch (IOException ex) {
   113             throw new MojoExecutionException("Problem converting JavaScriptXXX annotations", ex);
   114         }
   115     }
   116     
   117     private void processClasses(ClassLoader l, File master, File f) throws IOException, MojoExecutionException {
   118         if (!f.exists()) {
   119             return;
   120         }
   121         if (f.isDirectory()) {
   122             boolean classes = new File(f, "net.java.html.js.classes").exists();
   123             File[] arr = f.listFiles();
   124             if (arr != null) {
   125                 for (File file : arr) {
   126                     if (classes || file.isDirectory()) {
   127                         processClasses(l, master, file);
   128                     }
   129                 }
   130             }
   131             return;
   132         }
   133         
   134         if (!f.getName().endsWith(".class")) {
   135             return;
   136         }
   137         
   138         byte[] arr = new byte[(int)f.length()];
   139         FileInputStream is = new FileInputStream(f);
   140         try {
   141             readArr(arr, is);
   142         } finally {
   143             is.close();
   144         }
   145 
   146         byte[] newArr = null;
   147         try {
   148             Class<?> fnUtils = l.loadClass("org.netbeans.html.boot.impl.FnUtils");
   149             Method transform = fnUtils.getMethod("transform", byte[].class, ClassLoader.class);
   150             
   151             newArr = (byte[]) transform.invoke(null, arr, l);
   152             if (newArr == null || newArr == arr) {
   153                 return;
   154             }
   155             filterClass(new File(f.getParentFile(), "net.java.html.js.classes"), f.getName());
   156             filterClass(master, f.getName());
   157         } catch (Exception ex) {
   158             throw new MojoExecutionException("Can't process " + f, ex);
   159         }
   160         getLog().info("Processing " + f);
   161         writeArr(f, newArr);        
   162     }
   163 
   164     private void writeArr(File f, byte[] newArr) throws IOException, FileNotFoundException {
   165         FileOutputStream os = new FileOutputStream(f);
   166         try {
   167             os.write(newArr);
   168         } finally {
   169             os.close();
   170         }
   171     }
   172 
   173     private static void readArr(byte[] arr, InputStream is) throws IOException {
   174         int off = 0;
   175         while (off< arr.length) {
   176             int read = is.read(arr, off, arr.length - off);
   177             if (read == -1) {
   178                 break;
   179             }
   180             off += read;
   181         }
   182     }
   183     
   184     private static void filterClass(File f, String className) throws IOException {
   185         if (!f.exists()) {
   186             return;
   187         }
   188         if (className.endsWith(".class")) {
   189             className = className.substring(0, className.length() - 6);
   190         }
   191         
   192         BufferedReader r = new BufferedReader(new FileReader(f));
   193         List<String> arr = new ArrayList<String>();
   194         boolean modified = false;
   195         for (;;) {
   196             String line = r.readLine();
   197             if (line == null) {
   198                 break;
   199             }
   200             if (line.endsWith(className)) {
   201                 modified = true;
   202                 continue;
   203             }
   204             arr.add(line);
   205         }
   206         r.close();
   207         
   208         if (modified) {
   209             if (arr.isEmpty()) {
   210                 f.delete();
   211             } else {
   212                 FileWriter w = new FileWriter(f);
   213                 for (String l : arr) {
   214                     w.write(l);
   215                     w.write("\n");
   216                 }
   217                 w.close();
   218             }
   219         }
   220     }
   221 }