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
jtulach@3
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jtulach@3
     3
 *
jaroslav@551
     4
 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
jtulach@3
     5
 *
jaroslav@358
     6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
jaroslav@358
     7
 * Other names may be trademarks of their respective owners.
jtulach@3
     8
 *
jaroslav@358
     9
 * The contents of this file are subject to the terms of either the GNU
jaroslav@358
    10
 * General Public License Version 2 only ("GPL") or the Common
jaroslav@358
    11
 * Development and Distribution License("CDDL") (collectively, the
jaroslav@358
    12
 * "License"). You may not use this file except in compliance with the
jaroslav@358
    13
 * License. You can obtain a copy of the License at
jaroslav@358
    14
 * http://www.netbeans.org/cddl-gplv2.html
jaroslav@358
    15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
jaroslav@358
    16
 * specific language governing permissions and limitations under the
jaroslav@358
    17
 * License.  When distributing the software, include this License Header
jaroslav@358
    18
 * Notice in each file and include the License file at
jaroslav@358
    19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
jaroslav@358
    20
 * particular file as subject to the "Classpath" exception as provided
jaroslav@358
    21
 * by Oracle in the GPL Version 2 section of the License file that
jaroslav@358
    22
 * accompanied this code. If applicable, add the following below the
jaroslav@358
    23
 * License Header, with the fields enclosed by brackets [] replaced by
jaroslav@358
    24
 * your own identifying information:
jaroslav@358
    25
 * "Portions Copyrighted [year] [name of copyright owner]"
jaroslav@358
    26
 *
jaroslav@358
    27
 * Contributor(s):
jaroslav@358
    28
 *
jaroslav@358
    29
 * The Original Software is NetBeans. The Initial Developer of the Original
jaroslav@551
    30
 * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
jaroslav@358
    31
 *
jaroslav@358
    32
 * If you wish your version of this file to be governed by only the CDDL
jaroslav@358
    33
 * or only the GPL Version 2, indicate your decision by adding
jaroslav@358
    34
 * "[Contributor] elects to include this software in this distribution
jaroslav@358
    35
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
jaroslav@358
    36
 * single choice of license, a recipient has the option to distribute
jaroslav@358
    37
 * your version of this file under either the CDDL, the GPL Version 2 or
jaroslav@358
    38
 * to extend the choice of license to its licensees as provided above.
jaroslav@358
    39
 * However, if you add GPL Version 2 code and therefore, elected the GPL
jaroslav@358
    40
 * Version 2 license, then the option applies only if the new code is
jaroslav@358
    41
 * made subject to such option by the copyright holder.
jtulach@3
    42
 */
jtulach@3
    43
package net.java.html.json;
jtulach@3
    44
jtulach@3
    45
import java.io.ByteArrayInputStream;
jtulach@3
    46
import java.io.ByteArrayOutputStream;
jtulach@3
    47
import java.io.IOException;
jtulach@3
    48
import java.io.InputStream;
jtulach@3
    49
import java.io.OutputStream;
jtulach@3
    50
import java.net.URI;
jtulach@3
    51
import java.net.URISyntaxException;
jtulach@3
    52
import java.util.ArrayList;
jtulach@3
    53
import java.util.Arrays;
jtulach@3
    54
import java.util.HashMap;
jtulach@3
    55
import java.util.List;
jaroslav@245
    56
import java.util.Locale;
jtulach@3
    57
import java.util.Map;
jtulach@3
    58
import java.util.regex.Matcher;
jtulach@3
    59
import java.util.regex.Pattern;
jtulach@3
    60
import javax.tools.Diagnostic;
jtulach@3
    61
import javax.tools.DiagnosticListener;
jtulach@3
    62
import javax.tools.FileObject;
jtulach@3
    63
import javax.tools.ForwardingJavaFileManager;
jtulach@3
    64
import javax.tools.JavaFileManager;
jtulach@3
    65
import javax.tools.JavaFileObject;
jtulach@3
    66
import javax.tools.JavaFileObject.Kind;
jtulach@3
    67
import javax.tools.SimpleJavaFileObject;
jtulach@3
    68
import javax.tools.StandardJavaFileManager;
jtulach@3
    69
import javax.tools.StandardLocation;
jtulach@3
    70
import javax.tools.ToolProvider;
jaroslav@245
    71
import static org.testng.Assert.assertFalse;
jaroslav@245
    72
import static org.testng.Assert.fail;
jtulach@3
    73
jtulach@3
    74
/**
jtulach@3
    75
 *
jtulach@3
    76
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jtulach@3
    77
 */
jtulach@3
    78
final class Compile implements DiagnosticListener<JavaFileObject> {
jaroslav@100
    79
    private final List<Diagnostic<? extends JavaFileObject>> errors = 
jaroslav@100
    80
            new ArrayList<Diagnostic<? extends JavaFileObject>>();
jtulach@3
    81
    private final Map<String, byte[]> classes;
jtulach@3
    82
    private final String pkg;
jtulach@3
    83
    private final String cls;
jtulach@3
    84
    private final String html;
jaroslav@68
    85
    private final String sourceLevel;
jtulach@3
    86
jaroslav@68
    87
    private Compile(String html, String code, String sl) throws IOException {
jtulach@3
    88
        this.pkg = findPkg(code);
jtulach@3
    89
        this.cls = findCls(code);
jtulach@3
    90
        this.html = html;
jaroslav@68
    91
        this.sourceLevel = sl;
jtulach@3
    92
        classes = compile(html, code);
jtulach@3
    93
    }
jtulach@3
    94
jtulach@3
    95
    /** Performs compilation of given HTML page and associated Java code
jtulach@3
    96
     */
jtulach@3
    97
    public static Compile create(String html, String code) throws IOException {
jaroslav@68
    98
        return create(html, code, "1.7");
jaroslav@68
    99
    }
jaroslav@68
   100
    static Compile create(String html, String code, String sourceLevel) throws IOException {
jaroslav@68
   101
        return new Compile(html, code, sourceLevel);
jtulach@3
   102
    }
jtulach@3
   103
    
jtulach@3
   104
    /** Checks for given class among compiled resources */
jtulach@3
   105
    public byte[] get(String res) {
jtulach@3
   106
        return classes.get(res);
jtulach@3
   107
    }
jtulach@3
   108
    
jtulach@3
   109
    /** Obtains errors created during compilation.
jtulach@3
   110
     */
jtulach@3
   111
    public List<Diagnostic<? extends JavaFileObject>> getErrors() {
jaroslav@100
   112
        List<Diagnostic<? extends JavaFileObject>> err;
jaroslav@100
   113
        err = new ArrayList<Diagnostic<? extends JavaFileObject>>();
jtulach@3
   114
        for (Diagnostic<? extends JavaFileObject> diagnostic : errors) {
jtulach@3
   115
            if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
jtulach@3
   116
                err.add(diagnostic);
jtulach@3
   117
            }
jtulach@3
   118
        }
jtulach@3
   119
        return err;
jtulach@3
   120
    }
jtulach@3
   121
    
jtulach@3
   122
    private Map<String, byte[]> compile(final String html, final String code) throws IOException {
jtulach@3
   123
        StandardJavaFileManager sjfm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(this, null, null);
jtulach@3
   124
jaroslav@100
   125
        final Map<String, ByteArrayOutputStream> class2BAOS;
jaroslav@100
   126
        class2BAOS = new HashMap<String, ByteArrayOutputStream>();
jtulach@3
   127
jtulach@3
   128
        JavaFileObject file = new SimpleJavaFileObject(URI.create("mem://mem"), Kind.SOURCE) {
jtulach@3
   129
            @Override
jtulach@3
   130
            public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
jtulach@3
   131
                return code;
jtulach@3
   132
            }
jtulach@3
   133
        };
jtulach@3
   134
        final JavaFileObject htmlFile = new SimpleJavaFileObject(URI.create("mem://mem2"), Kind.OTHER) {
jtulach@3
   135
            @Override
jtulach@3
   136
            public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
jtulach@3
   137
                return html;
jtulach@3
   138
            }
jtulach@3
   139
jtulach@3
   140
            @Override
jtulach@3
   141
            public InputStream openInputStream() throws IOException {
jtulach@3
   142
                return new ByteArrayInputStream(html.getBytes());
jtulach@3
   143
            }
jtulach@3
   144
        };
jtulach@3
   145
        
jtulach@3
   146
        final URI scratch;
jtulach@3
   147
        try {
jtulach@3
   148
            scratch = new URI("mem://mem3");
jtulach@3
   149
        } catch (URISyntaxException ex) {
jtulach@3
   150
            throw new IOException(ex);
jtulach@3
   151
        }
jtulach@3
   152
        
jtulach@3
   153
        JavaFileManager jfm = new ForwardingJavaFileManager<JavaFileManager>(sjfm) {
jtulach@3
   154
            @Override
jtulach@3
   155
            public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
jtulach@3
   156
                if (kind  == Kind.CLASS) {
jtulach@3
   157
                    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
jtulach@3
   158
jtulach@3
   159
                    class2BAOS.put(className.replace('.', '/') + ".class", buffer);
jtulach@3
   160
                    return new SimpleJavaFileObject(sibling.toUri(), kind) {
jtulach@3
   161
                        @Override
jtulach@3
   162
                        public OutputStream openOutputStream() throws IOException {
jtulach@3
   163
                            return buffer;
jtulach@3
   164
                        }
jtulach@3
   165
                    };
jtulach@3
   166
                }
jtulach@3
   167
                
jtulach@3
   168
                if (kind == Kind.SOURCE) {
jtulach@3
   169
                    final String n = className.replace('.', '/') + ".java";
jaroslav@68
   170
                    final URI un;
jaroslav@68
   171
                    try {
jaroslav@68
   172
                        un = new URI("mem://" + n);
jaroslav@68
   173
                    } catch (URISyntaxException ex) {
jaroslav@68
   174
                        throw new IOException(ex);
jaroslav@68
   175
                    }
jaroslav@70
   176
                    return new VirtFO(un/*sibling.toUri()*/, kind, n);
jtulach@3
   177
                }
jtulach@3
   178
                
jtulach@3
   179
                throw new IllegalStateException();
jtulach@3
   180
            }
jtulach@3
   181
jtulach@3
   182
            @Override
jtulach@3
   183
            public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
jtulach@3
   184
                if (location == StandardLocation.SOURCE_PATH) {
jtulach@3
   185
                    if (packageName.equals(pkg)) {
jtulach@3
   186
                        return htmlFile;
jtulach@3
   187
                    }
jtulach@3
   188
                }
jtulach@3
   189
                
jtulach@3
   190
                return null;
jtulach@3
   191
            }
jaroslav@70
   192
jaroslav@70
   193
            @Override
jaroslav@70
   194
            public boolean isSameFile(FileObject a, FileObject b) {
jaroslav@70
   195
                if (a instanceof VirtFO && b instanceof VirtFO) {
jaroslav@70
   196
                    return ((VirtFO)a).getName().equals(((VirtFO)b).getName());
jaroslav@70
   197
                }
jaroslav@70
   198
                
jaroslav@70
   199
                return super.isSameFile(a, b);
jaroslav@70
   200
            }
jaroslav@70
   201
jaroslav@70
   202
            class VirtFO extends SimpleJavaFileObject {
jaroslav@70
   203
jaroslav@70
   204
                private final String n;
jaroslav@70
   205
jaroslav@70
   206
                public VirtFO(URI uri, Kind kind, String n) {
jaroslav@70
   207
                    super(uri, kind);
jaroslav@70
   208
                    this.n = n;
jaroslav@70
   209
                }
jaroslav@70
   210
                private final ByteArrayOutputStream data = new ByteArrayOutputStream();
jaroslav@70
   211
jaroslav@70
   212
                @Override
jaroslav@70
   213
                public OutputStream openOutputStream() throws IOException {
jaroslav@70
   214
                    return data;
jaroslav@70
   215
                }
jaroslav@70
   216
jaroslav@70
   217
                @Override
jaroslav@70
   218
                public String getName() {
jaroslav@70
   219
                    return n;
jaroslav@70
   220
                }
jaroslav@70
   221
jaroslav@70
   222
                @Override
jaroslav@70
   223
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
jaroslav@70
   224
                    data.close();
jaroslav@70
   225
                    return new String(data.toByteArray());
jaroslav@70
   226
                }
jaroslav@70
   227
            }
jtulach@3
   228
        };
jtulach@3
   229
jaroslav@68
   230
        ToolProvider.getSystemJavaCompiler().getTask(null, jfm, this, /*XXX:*/Arrays.asList("-source", sourceLevel, "-target", "1.7"), null, Arrays.asList(file)).call();
jtulach@3
   231
jaroslav@100
   232
        Map<String, byte[]> result = new HashMap<String, byte[]>();
jtulach@3
   233
jtulach@3
   234
        for (Map.Entry<String, ByteArrayOutputStream> e : class2BAOS.entrySet()) {
jtulach@3
   235
            result.put(e.getKey(), e.getValue().toByteArray());
jtulach@3
   236
        }
jtulach@3
   237
jtulach@3
   238
        return result;
jtulach@3
   239
    }
jtulach@3
   240
jtulach@3
   241
jtulach@3
   242
    @Override
jtulach@3
   243
    public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
jtulach@3
   244
        errors.add(diagnostic);
jtulach@3
   245
    }
jtulach@3
   246
    private static String findPkg(String java) throws IOException {
jtulach@3
   247
        Pattern p = Pattern.compile("package\\p{javaWhitespace}*([\\p{Alnum}\\.]+)\\p{javaWhitespace}*;", Pattern.MULTILINE);
jtulach@3
   248
        Matcher m = p.matcher(java);
jtulach@3
   249
        if (!m.find()) {
jtulach@3
   250
            throw new IOException("Can't find package declaration in the java file");
jtulach@3
   251
        }
jtulach@3
   252
        String pkg = m.group(1);
jtulach@3
   253
        return pkg;
jtulach@3
   254
    }
jtulach@3
   255
    private static String findCls(String java) throws IOException {
jtulach@3
   256
        Pattern p = Pattern.compile("class\\p{javaWhitespace}*([\\p{Alnum}\\.]+)\\p{javaWhitespace}", Pattern.MULTILINE);
jtulach@3
   257
        Matcher m = p.matcher(java);
jtulach@3
   258
        if (!m.find()) {
jtulach@3
   259
            throw new IOException("Can't find package declaration in the java file");
jtulach@3
   260
        }
jtulach@3
   261
        String cls = m.group(1);
jtulach@3
   262
        return cls;
jtulach@3
   263
    }
jtulach@3
   264
jtulach@3
   265
    String getHtml() {
jtulach@3
   266
        String fqn = "'" + pkg + '.' + cls + "'";
jtulach@3
   267
        return html.replace("'${fqn}'", fqn);
jtulach@3
   268
    }
jaroslav@245
   269
    void assertErrors() {
jaroslav@245
   270
        assertFalse(getErrors().isEmpty(), "There are supposed to be some errors");
jaroslav@245
   271
    }
jaroslav@245
   272
jaroslav@245
   273
    void assertError(String expMsg) {
jaroslav@245
   274
        StringBuilder sb = new StringBuilder();
jaroslav@245
   275
        sb.append("Can't find ").append(expMsg).append(" among:");
jaroslav@245
   276
        for (Diagnostic<? extends JavaFileObject> e : errors) {
jaroslav@245
   277
            String msg = e.getMessage(Locale.US);
jaroslav@245
   278
            if (msg.contains(expMsg)) {
jaroslav@245
   279
                return;
jaroslav@245
   280
            }
jaroslav@245
   281
            sb.append("\n");
jaroslav@245
   282
            sb.append(msg);
jaroslav@245
   283
        }
jaroslav@245
   284
        fail(sb.toString());
jaroslav@245
   285
    }
jtulach@3
   286
}