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