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