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