ko4j/src/test/java/org/netbeans/html/ko4j/KnockoutFXTest.java
author Jaroslav Tulach <jtulach@netbeans.org>
Tue, 26 Aug 2014 18:13:30 +0200
changeset 838 bdc3d696dd4a
parent 790 30f20d9c0986
child 869 aa80e696589c
child 886 88d62267a0b5
permissions -rw-r--r--
During the API review process (bug 246133) the reviewers decided that in order to include html4j to NetBeans Platform, we need to stop using org.apidesign namespace and switch to NetBeans one. Repackaging all SPI packages into org.netbeans.html.smthng.spi.
     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.ko4j;
    44 
    45 import java.io.BufferedReader;
    46 import java.io.IOException;
    47 import java.io.InputStreamReader;
    48 import java.lang.annotation.Annotation;
    49 import java.lang.reflect.Method;
    50 import java.net.URI;
    51 import java.net.URISyntaxException;
    52 import java.net.URL;
    53 import java.net.URLConnection;
    54 import java.util.ArrayList;
    55 import java.util.List;
    56 import java.util.Map;
    57 import java.util.concurrent.Executor;
    58 import java.util.concurrent.Executors;
    59 import net.java.html.BrwsrCtx;
    60 import net.java.html.boot.BrowserBuilder;
    61 import net.java.html.js.JavaScriptBody;
    62 import org.netbeans.html.boot.spi.Fn;
    63 import org.netbeans.html.context.spi.Contexts;
    64 import org.netbeans.html.json.spi.Technology;
    65 import org.netbeans.html.json.spi.Transfer;
    66 import org.netbeans.html.json.spi.WSTransfer;
    67 import org.netbeans.html.json.tck.KOTest;
    68 import org.netbeans.html.json.tck.KnockoutTCK;
    69 import org.netbeans.html.boot.impl.FnContext;
    70 import org.openide.util.lookup.ServiceProvider;
    71 import org.testng.Assert;
    72 import static org.testng.Assert.*;
    73 import org.testng.annotations.Factory;
    74 
    75 /**
    76  *
    77  * @author Jaroslav Tulach
    78  */
    79 @ServiceProvider(service = KnockoutTCK.class)
    80 public final class KnockoutFXTest extends KnockoutTCK {
    81     private static Class<?> browserClass;
    82     private static Fn.Presenter browserContext;
    83     
    84     public KnockoutFXTest() {
    85     }
    86     
    87     @Factory public static Object[] compatibilityTests() throws Exception {
    88         Class[] arr = testClasses();
    89         for (int i = 0; i < arr.length; i++) {
    90             assertEquals(
    91                 arr[i].getClassLoader(),
    92                 KnockoutFXTest.class.getClassLoader(),
    93                 "All classes loaded by the same classloader"
    94             );
    95         }
    96         
    97         URI uri = DynamicHTTP.initServer();
    98     
    99         final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutFXTest.class).
   100             loadPage(uri.toString()).
   101             invoke("initialized");
   102         
   103         Executors.newSingleThreadExecutor().submit(new Runnable() {
   104             @Override
   105             public void run() {
   106                 bb.showAndWait();
   107             }
   108         });
   109         
   110         ClassLoader l = getClassLoader();
   111         List<Object> res = new ArrayList<Object>();
   112         for (int i = 0; i < arr.length; i++) {
   113             Class<?> c = Class.forName(arr[i].getName(), true, l);
   114             seekKOTests(c, res);
   115         }
   116         Class<?> c = Class.forName(LessCallbacksCheck.class.getName(), true, l);
   117         seekKOTests(c, res);
   118         return res.toArray();
   119     }
   120 
   121     private static void seekKOTests(Class<?> c, List<Object> res) throws SecurityException, ClassNotFoundException {
   122         Class<? extends Annotation> koTest =
   123             c.getClassLoader().loadClass(KOTest.class.getName()).
   124             asSubclass(Annotation.class);
   125         for (Method m : c.getMethods()) {
   126             if (m.getAnnotation(koTest) != null) {
   127                 res.add(new KOFx(browserContext, m));
   128             }
   129         }
   130     }
   131 
   132     static synchronized ClassLoader getClassLoader() throws InterruptedException {
   133         while (browserClass == null) {
   134             KnockoutFXTest.class.wait();
   135         }
   136         return browserClass.getClassLoader();
   137     }
   138     
   139     public static synchronized void initialized(Class<?> browserCls) throws Exception {
   140         browserClass = browserCls;
   141         browserContext = Fn.activePresenter();
   142         KnockoutFXTest.class.notifyAll();
   143     }
   144     
   145     public static void initialized() throws Exception {
   146         Assert.assertSame(
   147             KnockoutFXTest.class.getClassLoader(),
   148             ClassLoader.getSystemClassLoader(),
   149             "No special classloaders"
   150         );
   151         KnockoutFXTest.initialized(KnockoutFXTest.class);
   152         browserContext = Fn.activePresenter();
   153     }
   154     
   155     @Override
   156     public BrwsrCtx createContext() {
   157         FXContext fx = new FXContext(browserContext);
   158         Contexts.Builder cb = Contexts.newBuilder().
   159             register(Technology.class, fx, 10).
   160             register(Transfer.class, fx, 10);
   161         if (fx.areWebSocketsSupported()) {
   162             cb.register(WSTransfer.class, fx, 10);
   163         }
   164         cb.register(Executor.class, (Executor)browserContext, 10);
   165         cb.register(Fn.Presenter.class, browserContext, 10);
   166         BrwsrCtx ctx = cb.build();
   167         return ctx;
   168     }
   169 
   170     @Override
   171     public Object createJSON(Map<String, Object> values) {
   172         Object json = createJSON();
   173         for (Map.Entry<String, Object> entry : values.entrySet()) {
   174             setProperty(json, entry.getKey(), entry.getValue());
   175         }
   176         return json;
   177     }
   178     
   179     @JavaScriptBody(args = {}, body = "return new Object();")
   180     private static native Object createJSON();
   181     @JavaScriptBody(args = { "json", "key", "value" }, body = "json[key] = value;")
   182     private static native void setProperty(Object json, String key, Object value);
   183 
   184     @Override
   185     @JavaScriptBody(args = { "s", "args" }, body = ""
   186         + "var f = new Function(s); "
   187         + "return f.apply(null, args);"
   188     )
   189     public native Object executeScript(String script, Object[] arguments);
   190 
   191     @JavaScriptBody(args = {  }, body = 
   192           "var h;"
   193         + "if (!!window && !!window.location && !!window.location.href)\n"
   194         + "  h = window.location.href;\n"
   195         + "else "
   196         + "  h = null;"
   197         + "return h;\n"
   198     )
   199     private static native String findBaseURL();
   200     
   201     @Override
   202     public URI prepareURL(String content, String mimeType, String[] parameters) {
   203         try {
   204             final URL baseURL = new URL(findBaseURL());
   205             StringBuilder sb = new StringBuilder();
   206             sb.append("/dynamic?mimeType=").append(mimeType);
   207             for (int i = 0; i < parameters.length; i++) {
   208                 sb.append("&param" + i).append("=").append(parameters[i]);
   209             }
   210             String mangle = content.replace("\n", "%0a")
   211                 .replace("\"", "\\\"").replace(" ", "%20");
   212             sb.append("&content=").append(mangle);
   213 
   214             URL query = new URL(baseURL, sb.toString());
   215             URLConnection c = query.openConnection();
   216             BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
   217             URI connectTo = new URI(br.readLine());
   218             return connectTo;
   219         } catch (IOException ex) {
   220             throw new IllegalStateException(ex);
   221         } catch (URISyntaxException ex) {
   222             throw new IllegalStateException(ex);
   223         }
   224     }
   225 
   226     @Override
   227     public boolean canFailWebSocketTest() {
   228         try {
   229             Class.forName("java.util.function.Function");
   230             return false;
   231         } catch (ClassNotFoundException ex) {
   232             // running on JDK7, FX WebView WebSocket impl does not work
   233             return true;
   234         }
   235     }
   236 }