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