ko-osgi-test/src/main/java/org/netbeans/html/ko/osgi/test/KnockoutEquinoxTCKImpl.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Fri, 07 Feb 2014 07:44:34 +0100
changeset 551 7ca2253fa86d
parent 444 03eeeb863fa1
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.ko.osgi.test;
    44 
    45 import java.io.BufferedReader;
    46 import java.io.IOException;
    47 import java.io.InputStreamReader;
    48 import java.lang.reflect.Constructor;
    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.Map;
    55 import java.util.concurrent.Callable;
    56 import java.util.concurrent.Executors;
    57 import net.java.html.BrwsrCtx;
    58 import net.java.html.boot.BrowserBuilder;
    59 import net.java.html.js.JavaScriptBody;
    60 import org.apidesign.html.boot.spi.Fn;
    61 import org.apidesign.html.context.spi.Contexts;
    62 import org.apidesign.html.json.spi.Technology;
    63 import org.apidesign.html.json.spi.Transfer;
    64 import org.apidesign.html.json.tck.KnockoutTCK;
    65 import org.json.JSONException;
    66 import org.json.JSONObject;
    67 import org.openide.util.lookup.ServiceProvider;
    68 import org.osgi.framework.Bundle;
    69 import org.osgi.framework.BundleContext;
    70 import org.osgi.framework.FrameworkUtil;
    71 
    72 /**
    73  *
    74  * @author Jaroslav Tulach <jtulach@netbeans.org>
    75  */
    76 @ServiceProvider(service = KnockoutTCK.class)
    77 public class KnockoutEquinoxTCKImpl extends KnockoutTCK implements Callable<Class[]> {
    78     
    79     private static Fn.Presenter browserContext;
    80 
    81     public static Class loadOSGiClass(String name, BundleContext ctx) throws Exception {
    82         for (Bundle b : ctx.getBundles()) {
    83             try {
    84                 Class<?> osgiClass = b.loadClass(name);
    85                 if (osgiClass != null && osgiClass.getClassLoader() != ClassLoader.getSystemClassLoader()) {
    86                     return osgiClass;
    87                 }
    88             } catch (ClassNotFoundException cnfe) {
    89                 // go on
    90             }
    91         }
    92         throw new IllegalStateException("Cannot load " + name + " from the OSGi container!");
    93     }
    94 
    95     @Override
    96     public Class[] call() throws Exception {
    97         return testClasses();
    98     }
    99     
   100     public static void start(URI server) throws Exception {
   101         final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutEquinoxTCKImpl.class).
   102             loadPage(server.toString()).
   103             invoke("initialized");
   104 
   105         Executors.newSingleThreadExecutor().submit(new Runnable() {
   106             @Override
   107             public void run() {
   108                 try {
   109                     final ClassLoader osgiClassLoader = BrowserBuilder.class.getClassLoader();
   110                     Thread.currentThread().setContextClassLoader(osgiClassLoader);
   111                     bb.showAndWait();
   112                 } catch (Throwable t) {
   113                     t.printStackTrace();
   114                 }
   115             }
   116         });
   117     }
   118 
   119     public static void initialized() throws Exception {
   120         Bundle bundle = FrameworkUtil.getBundle(KnockoutEquinoxTCKImpl.class);
   121         if (bundle == null) {
   122             throw new IllegalStateException(
   123                 "Should be loaded from a bundle. But was: " + KnockoutEquinoxTCKImpl.class.getClassLoader()
   124             );
   125         }
   126         Class<?> classpathClass = ClassLoader.getSystemClassLoader().loadClass(
   127             "org.netbeans.html.ko.osgi.test.KnockoutEquinoxIT"
   128         );
   129         Method m = classpathClass.getMethod("initialized", Class.class, Object.class);
   130         browserContext = Fn.activePresenter();
   131         m.invoke(null, KnockoutEquinoxTCKImpl.class, browserContext);
   132     }
   133     
   134     @Override
   135     public BrwsrCtx createContext() {
   136         try {
   137             Class<?> fxCls = loadOSGiClass(
   138                 "org.netbeans.html.ko4j.FXContext",
   139                 FrameworkUtil.getBundle(KnockoutEquinoxTCKImpl.class).getBundleContext()
   140             );
   141             final Constructor<?> cnstr = fxCls.getConstructor(Fn.Presenter.class);
   142             cnstr.setAccessible(true);
   143             Object fx = cnstr.newInstance(browserContext);
   144             Contexts.Builder cb = Contexts.newBuilder().
   145                 register(Technology.class, (Technology)fx, 10).
   146                 register(Transfer.class, (Transfer)fx, 10);
   147 //        if (fx.areWebSocketsSupported()) {
   148 //            cb.register(WSTransfer.class, fx, 10);
   149 //        }
   150             return cb.build();
   151         } catch (Exception ex) {
   152             throw new IllegalStateException(ex);
   153         }
   154     }
   155 
   156     @Override
   157     public Object createJSON(Map<String, Object> values) {
   158         JSONObject json = new JSONObject();
   159         for (Map.Entry<String, Object> entry : values.entrySet()) {
   160             try {
   161                 json.put(entry.getKey(), entry.getValue());
   162             } catch (JSONException ex) {
   163                 throw new IllegalStateException(ex);
   164             }
   165         }
   166         return json;
   167     }
   168 
   169     @Override
   170     @JavaScriptBody(args = { "s", "args" }, body = ""
   171         + "var f = new Function(s); "
   172         + "return f.apply(null, args);"
   173     )
   174     public native Object executeScript(String script, Object[] arguments);
   175 
   176     @JavaScriptBody(args = {  }, body = 
   177           "var h;"
   178         + "if (!!window && !!window.location && !!window.location.href)\n"
   179         + "  h = window.location.href;\n"
   180         + "else "
   181         + "  h = null;"
   182         + "return h;\n"
   183     )
   184     private static native String findBaseURL();
   185     
   186     @Override
   187     public URI prepareURL(String content, String mimeType, String[] parameters) {
   188         try {
   189             final URL baseURL = new URL(findBaseURL());
   190             StringBuilder sb = new StringBuilder();
   191             sb.append("/dynamic?mimeType=").append(mimeType);
   192             for (int i = 0; i < parameters.length; i++) {
   193                 sb.append("&param" + i).append("=").append(parameters[i]);
   194             }
   195             String mangle = content.replace("\n", "%0a")
   196                 .replace("\"", "\\\"").replace(" ", "%20");
   197             sb.append("&content=").append(mangle);
   198 
   199             URL query = new URL(baseURL, sb.toString());
   200             URLConnection c = query.openConnection();
   201             BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
   202             URI connectTo = new URI(br.readLine());
   203             return connectTo;
   204         } catch (IOException ex) {
   205             throw new IllegalStateException(ex);
   206         } catch (URISyntaxException ex) {
   207             throw new IllegalStateException(ex);
   208         }
   209     }
   210 
   211     @Override
   212     public boolean canFailWebSocketTest() {
   213         try {
   214             Class.forName("java.util.function.Function");
   215             return false;
   216         } catch (ClassNotFoundException ex) {
   217             // running on JDK7, FX WebView WebSocket impl does not work
   218             return true;
   219         }
   220     }
   221 
   222 }