ko-felix-test/src/main/java/org/netbeans/html/ko/felix/test/KnockoutFelixTCKImpl.java
author Jaroslav Tulach <jtulach@netbeans.org>
Tue, 26 Aug 2014 18:13:30 +0200
changeset 838 bdc3d696dd4a
parent 790 30f20d9c0986
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.ko.felix.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.ArrayList;
    55 import java.util.Collections;
    56 import java.util.Enumeration;
    57 import java.util.List;
    58 import java.util.Map;
    59 import java.util.concurrent.Callable;
    60 import java.util.concurrent.Executor;
    61 import java.util.concurrent.Executors;
    62 import net.java.html.BrwsrCtx;
    63 import net.java.html.boot.BrowserBuilder;
    64 import net.java.html.js.JavaScriptBody;
    65 import org.netbeans.html.boot.spi.Fn;
    66 import org.netbeans.html.context.spi.Contexts;
    67 import org.netbeans.html.json.spi.Technology;
    68 import org.netbeans.html.json.spi.Transfer;
    69 import org.netbeans.html.json.tck.KnockoutTCK;
    70 import org.json.JSONException;
    71 import org.json.JSONObject;
    72 import org.openide.util.lookup.ServiceProvider;
    73 import org.osgi.framework.Bundle;
    74 import org.osgi.framework.BundleContext;
    75 import org.osgi.framework.FrameworkUtil;
    76 
    77 /**
    78  *
    79  * @author Jaroslav Tulach
    80  */
    81 @ServiceProvider(service = KnockoutTCK.class)
    82 public class KnockoutFelixTCKImpl extends KnockoutTCK implements Callable<Class[]> {
    83     
    84     private static Fn.Presenter browserContext;
    85 
    86     public static Class loadOSGiClass(String name, BundleContext ctx) throws Exception {
    87         for (Bundle b : ctx.getBundles()) {
    88             try {
    89                 Class<?> osgiClass = b.loadClass(name);
    90                 if (osgiClass != null && osgiClass.getClassLoader() != ClassLoader.getSystemClassLoader()) {
    91                     return osgiClass;
    92                 }
    93             } catch (ClassNotFoundException cnfe) {
    94                 // go on
    95             }
    96         }
    97         throw new IllegalStateException("Cannot load " + name + " from the OSGi container!");
    98     }
    99 
   100     @Override
   101     public Class[] call() throws Exception {
   102         return testClasses();
   103     }
   104     
   105     public static void start(URI server) throws Exception {
   106         final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutFelixTCKImpl.class).
   107             loadPage(server.toString()).
   108             invoke("initialized");
   109 
   110         Executors.newSingleThreadExecutor().submit(new Runnable() {
   111             @Override
   112             public void run() {
   113                 try {
   114                     Bundle[] arr = FrameworkUtil.getBundle(BrowserBuilder.class).getBundleContext().getBundles();
   115                     final ClassLoader osgiClassLoader = new AllBundlesLoader(arr);
   116                     bb.classloader(osgiClassLoader);
   117                     bb.showAndWait();
   118                 } catch (Throwable t) {
   119                     t.printStackTrace();
   120                 }
   121             }
   122         });
   123     }
   124 
   125     public static void initialized() throws Exception {
   126         Bundle bundle = FrameworkUtil.getBundle(KnockoutFelixTCKImpl.class);
   127         if (bundle == null) {
   128             throw new IllegalStateException(
   129                 "Should be loaded from a bundle. But was: " + KnockoutFelixTCKImpl.class.getClassLoader()
   130             );
   131         }
   132         Class<?> classpathClass = ClassLoader.getSystemClassLoader().loadClass(
   133             "org.netbeans.html.ko.felix.test.KnockoutFelixIT"
   134         );
   135         Method m = classpathClass.getMethod("initialized", Class.class, Object.class);
   136         browserContext = Fn.activePresenter();
   137         m.invoke(null, KnockoutFelixTCKImpl.class, browserContext);
   138     }
   139     
   140     @Override
   141     public BrwsrCtx createContext() {
   142         try {
   143             Class<?> fxCls = loadOSGiClass(
   144                 "org.netbeans.html.ko4j.FXContext",
   145                 FrameworkUtil.getBundle(KnockoutFelixTCKImpl.class).getBundleContext()
   146             );
   147             final Constructor<?> cnstr = fxCls.getConstructor(Fn.Presenter.class);
   148             cnstr.setAccessible(true);
   149             Object fx = cnstr.newInstance(browserContext);
   150             Contexts.Builder cb = Contexts.newBuilder().
   151                 register(Technology.class, (Technology)fx, 10).
   152                 register(Transfer.class, (Transfer)fx, 10).
   153                 register(Executor.class, (Executor)browserContext, 10);
   154 //        if (fx.areWebSocketsSupported()) {
   155 //            cb.register(WSTransfer.class, fx, 10);
   156 //        }
   157             return cb.build();
   158         } catch (Exception ex) {
   159             throw new IllegalStateException(ex);
   160         }
   161     }
   162 
   163     @Override
   164     public Object createJSON(Map<String, Object> values) {
   165         JSONObject json = new JSONObject();
   166         for (Map.Entry<String, Object> entry : values.entrySet()) {
   167             try {
   168                 json.put(entry.getKey(), entry.getValue());
   169             } catch (JSONException ex) {
   170                 throw new IllegalStateException(ex);
   171             }
   172         }
   173         return json;
   174     }
   175 
   176     @Override
   177     @JavaScriptBody(args = { "s", "args" }, body = ""
   178         + "var f = new Function(s); "
   179         + "return f.apply(null, args);"
   180     )
   181     public native Object executeScript(String script, Object[] arguments);
   182 
   183     @JavaScriptBody(args = {  }, body = 
   184           "var h;"
   185         + "if (!!window && !!window.location && !!window.location.href)\n"
   186         + "  h = window.location.href;\n"
   187         + "else "
   188         + "  h = null;"
   189         + "return h;\n"
   190     )
   191     private static native String findBaseURL();
   192     
   193     @Override
   194     public URI prepareURL(String content, String mimeType, String[] parameters) {
   195         try {
   196             final URL baseURL = new URL(findBaseURL());
   197             StringBuilder sb = new StringBuilder();
   198             sb.append("/dynamic?mimeType=").append(mimeType);
   199             for (int i = 0; i < parameters.length; i++) {
   200                 sb.append("&param" + i).append("=").append(parameters[i]);
   201             }
   202             String mangle = content.replace("\n", "%0a")
   203                 .replace("\"", "\\\"").replace(" ", "%20");
   204             sb.append("&content=").append(mangle);
   205 
   206             URL query = new URL(baseURL, sb.toString());
   207             URLConnection c = query.openConnection();
   208             BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
   209             URI connectTo = new URI(br.readLine());
   210             return connectTo;
   211         } catch (IOException ex) {
   212             throw new IllegalStateException(ex);
   213         } catch (URISyntaxException ex) {
   214             throw new IllegalStateException(ex);
   215         }
   216     }
   217 
   218     @Override
   219     public boolean canFailWebSocketTest() {
   220         return true;
   221     }
   222 
   223     private static final class AllBundlesLoader extends ClassLoader {
   224         private final Bundle[] arr;
   225 
   226         public AllBundlesLoader(Bundle[] arr) {
   227             super(ClassLoader.getSystemClassLoader().getParent());
   228             this.arr = arr;
   229         }
   230 
   231         @Override
   232         public Class<?> loadClass(String name) throws ClassNotFoundException {
   233             return loadClass(name, false);
   234         }
   235 
   236         @Override
   237         protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
   238             ClassNotFoundException err = null;
   239             for (Bundle b : arr) {
   240                 try {
   241                     Class<?> cls = b.loadClass(name);
   242                     if (FrameworkUtil.getBundle(cls) == b) {
   243                         return cls;
   244                     }
   245                 } catch (ClassNotFoundException ex) {
   246                     err = ex;
   247                 }
   248             }
   249             throw err;
   250         }
   251 
   252         @Override
   253         protected URL findResource(String name) {
   254             for (Bundle b : arr) {
   255                 URL r = b.getResource(name);
   256                 if (r != null) {
   257                     return r;
   258                 }
   259             }
   260             return null;
   261         }
   262 
   263         @Override
   264         protected Enumeration<URL> findResources(String name) throws IOException {
   265             List<URL> ret = new ArrayList<URL>();
   266             for (Bundle b : arr) {
   267                 Enumeration<URL> en = b.getResources(name);
   268                 if (en != null) while (en.hasMoreElements()) {
   269                     URL u = en.nextElement();
   270                     ret.add(u);
   271                 }
   272             }
   273             return Collections.enumeration(ret);
   274         }
   275         
   276         
   277         
   278     }
   279 }