ko-felix-test/src/main/java/org/netbeans/html/ko/felix/test/KnockoutFelixTCKImpl.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 26 Nov 2015 20:59:51 +0100
changeset 1021 c918924ad3c5
parent 934 bbbdf003a99b
permissions -rw-r--r--
#256696: Making OSGi headers, enterprise OSGi ready
     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.InvocationTargetException;
    50 import java.lang.reflect.Method;
    51 import java.net.URI;
    52 import java.net.URISyntaxException;
    53 import java.net.URL;
    54 import java.net.URLConnection;
    55 import java.util.ArrayList;
    56 import java.util.Collections;
    57 import java.util.Enumeration;
    58 import java.util.List;
    59 import java.util.Map;
    60 import java.util.concurrent.Callable;
    61 import java.util.concurrent.Executor;
    62 import java.util.concurrent.Executors;
    63 import net.java.html.BrwsrCtx;
    64 import net.java.html.boot.BrowserBuilder;
    65 import net.java.html.js.JavaScriptBody;
    66 import org.netbeans.html.boot.spi.Fn;
    67 import org.netbeans.html.context.spi.Contexts;
    68 import org.netbeans.html.json.spi.Technology;
    69 import org.netbeans.html.json.spi.Transfer;
    70 import org.netbeans.html.json.tck.KnockoutTCK;
    71 import org.openide.util.lookup.ServiceProvider;
    72 import org.osgi.framework.Bundle;
    73 import org.osgi.framework.BundleContext;
    74 import org.osgi.framework.FrameworkUtil;
    75 
    76 /**
    77  *
    78  * @author Jaroslav Tulach
    79  */
    80 @ServiceProvider(service = KnockoutTCK.class)
    81 public class KnockoutFelixTCKImpl extends KnockoutTCK implements Callable<Class[]> {
    82     
    83     private static Fn.Presenter browserContext;
    84 
    85     public static Class loadOSGiClass(String name, BundleContext ctx) throws Exception {
    86         for (Bundle b : ctx.getBundles()) {
    87             try {
    88                 Class<?> osgiClass = b.loadClass(name);
    89                 if (osgiClass != null && osgiClass.getClassLoader() != ClassLoader.getSystemClassLoader()) {
    90                     return osgiClass;
    91                 }
    92             } catch (ClassNotFoundException cnfe) {
    93                 // go on
    94             }
    95         }
    96         throw new IllegalStateException("Cannot load " + name + " from the OSGi container!");
    97     }
    98 
    99     @Override
   100     public Class[] call() throws Exception {
   101         return testClasses();
   102     }
   103     
   104     public static void start(String callBackClass, URI server, final boolean useAllClassloader) throws Exception {
   105         final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutFelixTCKImpl.class).
   106             loadPage(server.toString()).
   107             invoke("initialized", callBackClass);
   108 
   109         Executors.newSingleThreadExecutor().submit(new Runnable() {
   110             @Override
   111             public void run() {
   112                 try {
   113                     Bundle[] arr = FrameworkUtil.getBundle(BrowserBuilder.class).getBundleContext().getBundles();
   114                     if (useAllClassloader) {
   115                         final ClassLoader osgiClassLoader = new AllBundlesLoader(arr);
   116                         bb.classloader(osgiClassLoader);
   117                     }
   118                     bb.showAndWait();
   119                 } catch (Throwable t) {
   120                     t.printStackTrace();
   121                 }
   122             }
   123         });
   124     }
   125 
   126     public static void initialized(String... args) throws Exception {
   127         Bundle bundle = FrameworkUtil.getBundle(KnockoutFelixTCKImpl.class);
   128         if (bundle == null) {
   129             throw new IllegalStateException(
   130                 "Should be loaded from a bundle. But was: " + KnockoutFelixTCKImpl.class.getClassLoader()
   131             );
   132         }
   133         Class<?> classpathClass = ClassLoader.getSystemClassLoader().loadClass(args[0]);
   134         Method m = classpathClass.getMethod("initialized", Class.class, Object.class);
   135         browserContext = Fn.activePresenter();
   136         m.invoke(null, KnockoutFelixTCKImpl.class, browserContext);
   137     }
   138     
   139     @Override
   140     public BrwsrCtx createContext() {
   141         try {
   142             Contexts.Builder cb = Contexts.newBuilder().
   143                 register(Technology.class, (Technology)osgiInstance("KOTech"), 10).
   144                 register(Transfer.class, (Transfer)osgiInstance("KOTransfer"), 10).
   145                 register(Executor.class, (Executor)browserContext, 10);
   146 //        if (fx.areWebSocketsSupported()) {
   147 //            cb.register(WSTransfer.class, fx, 10);
   148 //        }
   149             return cb.build();
   150         } catch (Exception ex) {
   151             throw new IllegalStateException(ex);
   152         }
   153     }
   154 
   155     private Object osgiInstance(String simpleName) throws IllegalAccessException, SecurityException, IllegalArgumentException, Exception, NoSuchMethodException, InstantiationException, InvocationTargetException {
   156         Class<?> fxCls = loadOSGiClass(
   157                 "org.netbeans.html.ko4j." + simpleName,
   158                 FrameworkUtil.getBundle(KnockoutFelixTCKImpl.class).getBundleContext()
   159         );
   160         final Constructor<?> cnstr = fxCls.getDeclaredConstructor();
   161         cnstr.setAccessible(true);
   162         Object fx = cnstr.newInstance();
   163         return fx;
   164     }
   165 
   166     @Override
   167     public Object createJSON(Map<String, Object> values) {
   168         Object json = createObj();
   169         for (Map.Entry<String, Object> entry : values.entrySet()) {
   170             putObj(json, entry.getKey(), entry.getValue());
   171         }
   172         return json;
   173     }
   174     
   175     @JavaScriptBody(args = {  }, body = "return {};")
   176     private static native Object createObj();
   177     @JavaScriptBody(args = { "obj", "prop", "val" }, body = "obj[prop] = val;")
   178     private static native void putObj(Object obj, String prop, Object val);
   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         return true;
   225     }
   226 
   227     private static final class AllBundlesLoader extends ClassLoader {
   228         private final Bundle[] arr;
   229 
   230         public AllBundlesLoader(Bundle[] arr) {
   231             super(ClassLoader.getSystemClassLoader().getParent());
   232             this.arr = arr;
   233         }
   234 
   235         @Override
   236         public Class<?> loadClass(String name) throws ClassNotFoundException {
   237             return loadClass(name, false);
   238         }
   239 
   240         @Override
   241         protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
   242             ClassNotFoundException err = null;
   243             for (Bundle b : arr) {
   244                 try {
   245                     Class<?> cls = b.loadClass(name);
   246                     if (FrameworkUtil.getBundle(cls) == b) {
   247                         return cls;
   248                     }
   249                 } catch (ClassNotFoundException ex) {
   250                     err = ex;
   251                 }
   252             }
   253             throw err;
   254         }
   255 
   256         @Override
   257         protected URL findResource(String name) {
   258             for (Bundle b : arr) {
   259                 URL r = b.getResource(name);
   260                 if (r != null) {
   261                     return r;
   262                 }
   263             }
   264             return null;
   265         }
   266 
   267         @Override
   268         protected Enumeration<URL> findResources(String name) throws IOException {
   269             List<URL> ret = new ArrayList<URL>();
   270             for (Bundle b : arr) {
   271                 Enumeration<URL> en = b.getResources(name);
   272                 if (en != null) while (en.hasMoreElements()) {
   273                     URL u = en.nextElement();
   274                     ret.add(u);
   275                 }
   276             }
   277             return Collections.enumeration(ret);
   278         }
   279         
   280         
   281         
   282     }
   283 }