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