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