boot/src/test/java/org/netbeans/html/boot/impl/Compile.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Fri, 07 Feb 2014 07:44:34 +0100
changeset 551 7ca2253fa86d
parent 531 ff48a4a875ff
child 790 30f20d9c0986
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.boot.impl;
    44 
    45 import java.io.ByteArrayInputStream;
    46 import java.io.ByteArrayOutputStream;
    47 import java.io.IOException;
    48 import java.io.InputStream;
    49 import java.io.OutputStream;
    50 import java.net.URI;
    51 import java.net.URISyntaxException;
    52 import java.util.ArrayList;
    53 import java.util.Arrays;
    54 import java.util.HashMap;
    55 import java.util.List;
    56 import java.util.Locale;
    57 import java.util.Map;
    58 import java.util.logging.Level;
    59 import java.util.logging.Logger;
    60 import java.util.regex.Matcher;
    61 import java.util.regex.Pattern;
    62 import javax.tools.Diagnostic;
    63 import javax.tools.DiagnosticListener;
    64 import javax.tools.FileObject;
    65 import javax.tools.ForwardingJavaFileManager;
    66 import javax.tools.JavaFileManager;
    67 import javax.tools.JavaFileObject;
    68 import javax.tools.JavaFileObject.Kind;
    69 import javax.tools.SimpleJavaFileObject;
    70 import javax.tools.StandardJavaFileManager;
    71 import javax.tools.StandardLocation;
    72 import javax.tools.ToolProvider;
    73 import static org.testng.Assert.assertTrue;
    74 import static org.testng.Assert.assertFalse;
    75 import static org.testng.Assert.fail;
    76 
    77 /**
    78  *
    79  * @author Jaroslav Tulach <jtulach@netbeans.org>
    80  */
    81 final class Compile implements DiagnosticListener<JavaFileObject> {
    82     private final List<Diagnostic<? extends JavaFileObject>> errors = 
    83             new ArrayList<Diagnostic<? extends JavaFileObject>>();
    84     private final Map<String, byte[]> classes;
    85     private final String pkg;
    86     private final String cls;
    87     private final String html;
    88     private final String sourceLevel;
    89 
    90     private Compile(String html, String code, String sl) throws IOException {
    91         this.pkg = findPkg(code);
    92         this.cls = findCls(code);
    93         this.html = html;
    94         this.sourceLevel = sl;
    95         classes = compile(html, code);
    96     }
    97 
    98     /** Performs compilation of given HTML page and associated Java code
    99      */
   100     public static Compile create(String html, String code) throws IOException {
   101         return create(html, code, "1.7");
   102     }
   103     static Compile create(String html, String code, String sourceLevel) throws IOException {
   104         return new Compile(html, code, sourceLevel);
   105     }
   106     
   107     /** Checks for given class among compiled resources */
   108     public byte[] get(String res) {
   109         return classes.get(res);
   110     }
   111     
   112     /** Obtains errors created during compilation.
   113      */
   114     public List<Diagnostic<? extends JavaFileObject>> getErrors() {
   115         List<Diagnostic<? extends JavaFileObject>> err;
   116         err = new ArrayList<Diagnostic<? extends JavaFileObject>>();
   117         for (Diagnostic<? extends JavaFileObject> diagnostic : errors) {
   118             if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
   119                 err.add(diagnostic);
   120             }
   121         }
   122         return err;
   123     }
   124     
   125     private Map<String, byte[]> compile(final String html, final String code) throws IOException {
   126         StandardJavaFileManager sjfm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(this, null, null);
   127 
   128         final Map<String, ByteArrayOutputStream> class2BAOS;
   129         class2BAOS = new HashMap<String, ByteArrayOutputStream>();
   130 
   131         JavaFileObject file = new SimpleJavaFileObject(URI.create("mem://mem"), Kind.SOURCE) {
   132             @Override
   133             public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
   134                 return code;
   135             }
   136         };
   137         final JavaFileObject htmlFile = new SimpleJavaFileObject(URI.create("mem://mem2"), Kind.OTHER) {
   138             @Override
   139             public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
   140                 return html;
   141             }
   142 
   143             @Override
   144             public InputStream openInputStream() throws IOException {
   145                 return new ByteArrayInputStream(html.getBytes());
   146             }
   147         };
   148         
   149         final URI scratch;
   150         try {
   151             scratch = new URI("mem://mem3");
   152         } catch (URISyntaxException ex) {
   153             throw new IOException(ex);
   154         }
   155         
   156         JavaFileManager jfm = new ForwardingJavaFileManager<JavaFileManager>(sjfm) {
   157             @Override
   158             public FileObject getFileForOutput(JavaFileManager.Location location, String packageName, String relativeName, FileObject sibling) throws IOException {
   159                 try {
   160                     return new VirtFO(new URI("mem://resource/" + relativeName), Kind.OTHER, relativeName);
   161                 } catch (URISyntaxException ex) {
   162                     throw new IllegalStateException(ex);
   163                 }
   164             }
   165             
   166             
   167             @Override
   168             public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
   169                 if (kind  == Kind.CLASS) {
   170                     final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
   171 
   172                     class2BAOS.put(className.replace('.', '/') + ".class", buffer);
   173                     return new SimpleJavaFileObject(sibling.toUri(), kind) {
   174                         @Override
   175                         public OutputStream openOutputStream() throws IOException {
   176                             return buffer;
   177                         }
   178                     };
   179                 }
   180                 
   181                 if (kind == Kind.SOURCE) {
   182                     final String n = className.replace('.', '/') + ".java";
   183                     final URI un;
   184                     try {
   185                         un = new URI("mem://" + n);
   186                     } catch (URISyntaxException ex) {
   187                         throw new IOException(ex);
   188                     }
   189                     return new VirtFO(un/*sibling.toUri()*/, kind, n);
   190                 }
   191                 
   192                 throw new IllegalStateException();
   193             }
   194 
   195             @Override
   196             public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
   197                 if (location == StandardLocation.SOURCE_PATH) {
   198                     if (packageName.equals(pkg)) {
   199                         return htmlFile;
   200                     }
   201                     if (packageName.isEmpty() && relativeName.startsWith(pkg.replace('.', '/'))) {
   202                         return htmlFile;
   203                     }
   204                 }
   205                 
   206                 return null;
   207             }
   208 
   209             @Override
   210             public boolean isSameFile(FileObject a, FileObject b) {
   211                 if (a instanceof VirtFO && b instanceof VirtFO) {
   212                     return ((VirtFO)a).getName().equals(((VirtFO)b).getName());
   213                 }
   214                 
   215                 return super.isSameFile(a, b);
   216             }
   217 
   218             class VirtFO extends SimpleJavaFileObject {
   219 
   220                 private final String n;
   221 
   222                 public VirtFO(URI uri, Kind kind, String n) {
   223                     super(uri, kind);
   224                     this.n = n;
   225                 }
   226                 private final ByteArrayOutputStream data = new ByteArrayOutputStream();
   227 
   228                 @Override
   229                 public OutputStream openOutputStream() throws IOException {
   230                     return data;
   231                 }
   232 
   233                 @Override
   234                 public String getName() {
   235                     return n;
   236                 }
   237 
   238                 @Override
   239                 public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
   240                     data.close();
   241                     return new String(data.toByteArray());
   242                 }
   243             }
   244         };
   245 
   246         ToolProvider.getSystemJavaCompiler().getTask(null, jfm, this, /*XXX:*/Arrays.asList("-source", sourceLevel, "-target", "1.7"), null, Arrays.asList(file)).call();
   247 
   248         Map<String, byte[]> result = new HashMap<String, byte[]>();
   249 
   250         for (Map.Entry<String, ByteArrayOutputStream> e : class2BAOS.entrySet()) {
   251             result.put(e.getKey(), e.getValue().toByteArray());
   252         }
   253 
   254         return result;
   255     }
   256 
   257 
   258     @Override
   259     public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   260         errors.add(diagnostic);
   261     }
   262     private static String findPkg(String java) throws IOException {
   263         Pattern p = Pattern.compile("package\\p{javaWhitespace}*([\\p{Alnum}\\.]+)\\p{javaWhitespace}*;", Pattern.MULTILINE);
   264         Matcher m = p.matcher(java);
   265         if (!m.find()) {
   266             throw new IOException("Can't find package declaration in the java file");
   267         }
   268         String pkg = m.group(1);
   269         return pkg;
   270     }
   271     private static String findCls(String java) throws IOException {
   272         Pattern p = Pattern.compile("class\\p{javaWhitespace}*([\\p{Alnum}\\.]+)\\p{javaWhitespace}", Pattern.MULTILINE);
   273         Matcher m = p.matcher(java);
   274         if (!m.find()) {
   275             throw new IOException("Can't find package declaration in the java file");
   276         }
   277         String cls = m.group(1);
   278         return cls;
   279     }
   280 
   281     String getHtml() {
   282         String fqn = "'" + pkg + '.' + cls + "'";
   283         return html.replace("'${fqn}'", fqn);
   284     }
   285     void assertErrors() {
   286         assertFalse(getErrors().isEmpty(), "There are supposed to be some errors");
   287     }
   288 
   289     void assertError(String expMsg) {
   290         StringBuilder sb = new StringBuilder();
   291         sb.append("Can't find ").append(expMsg).append(" among:");
   292         for (Diagnostic<? extends JavaFileObject> e : errors) {
   293             String msg = e.getMessage(Locale.US);
   294             if (msg.contains(expMsg)) {
   295                 return;
   296             }
   297             sb.append("\n");
   298             sb.append(msg);
   299         }
   300         fail(sb.toString());
   301     }
   302 
   303     void assertNoErrors() {
   304         assertTrue(getErrors().isEmpty(), "No errors expected: " + getErrors());
   305     }
   306 }