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
jaroslav@370
     1
/**
jaroslav@370
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@370
     3
 *
jaroslav@551
     4
 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
jaroslav@370
     5
 *
jaroslav@370
     6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
jaroslav@370
     7
 * Other names may be trademarks of their respective owners.
jaroslav@370
     8
 *
jaroslav@370
     9
 * The contents of this file are subject to the terms of either the GNU
jaroslav@370
    10
 * General Public License Version 2 only ("GPL") or the Common
jaroslav@370
    11
 * Development and Distribution License("CDDL") (collectively, the
jaroslav@370
    12
 * "License"). You may not use this file except in compliance with the
jaroslav@370
    13
 * License. You can obtain a copy of the License at
jaroslav@370
    14
 * http://www.netbeans.org/cddl-gplv2.html
jaroslav@370
    15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
jaroslav@370
    16
 * specific language governing permissions and limitations under the
jaroslav@370
    17
 * License.  When distributing the software, include this License Header
jaroslav@370
    18
 * Notice in each file and include the License file at
jaroslav@370
    19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
jaroslav@370
    20
 * particular file as subject to the "Classpath" exception as provided
jaroslav@370
    21
 * by Oracle in the GPL Version 2 section of the License file that
jaroslav@370
    22
 * accompanied this code. If applicable, add the following below the
jaroslav@370
    23
 * License Header, with the fields enclosed by brackets [] replaced by
jaroslav@370
    24
 * your own identifying information:
jaroslav@370
    25
 * "Portions Copyrighted [year] [name of copyright owner]"
jaroslav@370
    26
 *
jaroslav@370
    27
 * Contributor(s):
jaroslav@370
    28
 *
jaroslav@370
    29
 * The Original Software is NetBeans. The Initial Developer of the Original
jaroslav@551
    30
 * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
jaroslav@370
    31
 *
jaroslav@370
    32
 * If you wish your version of this file to be governed by only the CDDL
jaroslav@370
    33
 * or only the GPL Version 2, indicate your decision by adding
jaroslav@370
    34
 * "[Contributor] elects to include this software in this distribution
jaroslav@370
    35
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
jaroslav@370
    36
 * single choice of license, a recipient has the option to distribute
jaroslav@370
    37
 * your version of this file under either the CDDL, the GPL Version 2 or
jaroslav@370
    38
 * to extend the choice of license to its licensees as provided above.
jaroslav@370
    39
 * However, if you add GPL Version 2 code and therefore, elected the GPL
jaroslav@370
    40
 * Version 2 license, then the option applies only if the new code is
jaroslav@370
    41
 * made subject to such option by the copyright holder.
jaroslav@370
    42
 */
jtulach@771
    43
package org.netbeans.html.ko.felix.test;
jaroslav@370
    44
jaroslav@371
    45
import java.io.BufferedReader;
jaroslav@370
    46
import java.io.IOException;
jaroslav@371
    47
import java.io.InputStreamReader;
jaroslav@444
    48
import java.lang.reflect.Constructor;
jtulach@886
    49
import java.lang.reflect.InvocationTargetException;
jaroslav@371
    50
import java.lang.reflect.Method;
jaroslav@371
    51
import java.net.URI;
jaroslav@371
    52
import java.net.URISyntaxException;
jaroslav@371
    53
import java.net.URL;
jaroslav@371
    54
import java.net.URLConnection;
jtulach@771
    55
import java.util.ArrayList;
jtulach@771
    56
import java.util.Collections;
jtulach@771
    57
import java.util.Enumeration;
jtulach@771
    58
import java.util.List;
jaroslav@370
    59
import java.util.Map;
jaroslav@371
    60
import java.util.concurrent.Callable;
jaroslav@574
    61
import java.util.concurrent.Executor;
jaroslav@396
    62
import java.util.concurrent.Executors;
jaroslav@370
    63
import net.java.html.BrwsrCtx;
jaroslav@396
    64
import net.java.html.boot.BrowserBuilder;
jaroslav@371
    65
import net.java.html.js.JavaScriptBody;
jtulach@838
    66
import org.netbeans.html.boot.spi.Fn;
jtulach@838
    67
import org.netbeans.html.context.spi.Contexts;
jtulach@838
    68
import org.netbeans.html.json.spi.Technology;
jtulach@838
    69
import org.netbeans.html.json.spi.Transfer;
jtulach@838
    70
import org.netbeans.html.json.tck.KnockoutTCK;
jaroslav@371
    71
import org.openide.util.lookup.ServiceProvider;
jaroslav@396
    72
import org.osgi.framework.Bundle;
jaroslav@396
    73
import org.osgi.framework.BundleContext;
jaroslav@396
    74
import org.osgi.framework.FrameworkUtil;
jaroslav@370
    75
jaroslav@370
    76
/**
jaroslav@370
    77
 *
jtulach@790
    78
 * @author Jaroslav Tulach
jaroslav@370
    79
 */
jaroslav@371
    80
@ServiceProvider(service = KnockoutTCK.class)
jtulach@771
    81
public class KnockoutFelixTCKImpl extends KnockoutTCK implements Callable<Class[]> {
jaroslav@371
    82
    
jaroslav@371
    83
    private static Fn.Presenter browserContext;
jaroslav@371
    84
jaroslav@396
    85
    public static Class loadOSGiClass(String name, BundleContext ctx) throws Exception {
jaroslav@396
    86
        for (Bundle b : ctx.getBundles()) {
jaroslav@396
    87
            try {
jaroslav@396
    88
                Class<?> osgiClass = b.loadClass(name);
jaroslav@396
    89
                if (osgiClass != null && osgiClass.getClassLoader() != ClassLoader.getSystemClassLoader()) {
jaroslav@396
    90
                    return osgiClass;
jaroslav@396
    91
                }
jaroslav@396
    92
            } catch (ClassNotFoundException cnfe) {
jaroslav@396
    93
                // go on
jaroslav@396
    94
            }
jaroslav@396
    95
        }
jaroslav@396
    96
        throw new IllegalStateException("Cannot load " + name + " from the OSGi container!");
jaroslav@396
    97
    }
jaroslav@396
    98
jaroslav@391
    99
    @Override
jaroslav@391
   100
    public Class[] call() throws Exception {
jaroslav@391
   101
        return testClasses();
jaroslav@371
   102
    }
jaroslav@396
   103
    
jtulach@1021
   104
    public static void start(String callBackClass, URI server, final boolean useAllClassloader) throws Exception {
jtulach@771
   105
        final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(KnockoutFelixTCKImpl.class).
jaroslav@396
   106
            loadPage(server.toString()).
jtulach@1021
   107
            invoke("initialized", callBackClass);
jaroslav@396
   108
jaroslav@396
   109
        Executors.newSingleThreadExecutor().submit(new Runnable() {
jaroslav@396
   110
            @Override
jaroslav@396
   111
            public void run() {
jaroslav@396
   112
                try {
jtulach@771
   113
                    Bundle[] arr = FrameworkUtil.getBundle(BrowserBuilder.class).getBundleContext().getBundles();
jtulach@1021
   114
                    if (useAllClassloader) {
jtulach@1021
   115
                        final ClassLoader osgiClassLoader = new AllBundlesLoader(arr);
jtulach@1021
   116
                        bb.classloader(osgiClassLoader);
jtulach@1021
   117
                    }
jaroslav@396
   118
                    bb.showAndWait();
jaroslav@396
   119
                } catch (Throwable t) {
jaroslav@396
   120
                    t.printStackTrace();
jaroslav@396
   121
                }
jaroslav@396
   122
            }
jaroslav@396
   123
        });
jaroslav@396
   124
    }
jaroslav@371
   125
jtulach@1021
   126
    public static void initialized(String... args) throws Exception {
jtulach@771
   127
        Bundle bundle = FrameworkUtil.getBundle(KnockoutFelixTCKImpl.class);
jaroslav@398
   128
        if (bundle == null) {
jaroslav@398
   129
            throw new IllegalStateException(
jtulach@771
   130
                "Should be loaded from a bundle. But was: " + KnockoutFelixTCKImpl.class.getClassLoader()
jaroslav@398
   131
            );
jaroslav@398
   132
        }
jtulach@1021
   133
        Class<?> classpathClass = ClassLoader.getSystemClassLoader().loadClass(args[0]);
jaroslav@396
   134
        Method m = classpathClass.getMethod("initialized", Class.class, Object.class);
jaroslav@391
   135
        browserContext = Fn.activePresenter();
jtulach@771
   136
        m.invoke(null, KnockoutFelixTCKImpl.class, browserContext);
jaroslav@371
   137
    }
jaroslav@371
   138
    
jaroslav@371
   139
    @Override
jaroslav@371
   140
    public BrwsrCtx createContext() {
jaroslav@391
   141
        try {
jaroslav@391
   142
            Contexts.Builder cb = Contexts.newBuilder().
jtulach@886
   143
                register(Technology.class, (Technology)osgiInstance("KOTech"), 10).
jtulach@886
   144
                register(Transfer.class, (Transfer)osgiInstance("KOTransfer"), 10).
jaroslav@574
   145
                register(Executor.class, (Executor)browserContext, 10);
jaroslav@371
   146
//        if (fx.areWebSocketsSupported()) {
jaroslav@371
   147
//            cb.register(WSTransfer.class, fx, 10);
jaroslav@371
   148
//        }
jaroslav@391
   149
            return cb.build();
jaroslav@391
   150
        } catch (Exception ex) {
jaroslav@391
   151
            throw new IllegalStateException(ex);
jaroslav@391
   152
        }
jaroslav@371
   153
    }
jaroslav@371
   154
jtulach@886
   155
    private Object osgiInstance(String simpleName) throws IllegalAccessException, SecurityException, IllegalArgumentException, Exception, NoSuchMethodException, InstantiationException, InvocationTargetException {
jtulach@886
   156
        Class<?> fxCls = loadOSGiClass(
jtulach@886
   157
                "org.netbeans.html.ko4j." + simpleName,
jtulach@886
   158
                FrameworkUtil.getBundle(KnockoutFelixTCKImpl.class).getBundleContext()
jtulach@886
   159
        );
jtulach@886
   160
        final Constructor<?> cnstr = fxCls.getDeclaredConstructor();
jtulach@886
   161
        cnstr.setAccessible(true);
jtulach@886
   162
        Object fx = cnstr.newInstance();
jtulach@886
   163
        return fx;
jtulach@886
   164
    }
jtulach@886
   165
jaroslav@371
   166
    @Override
jaroslav@371
   167
    public Object createJSON(Map<String, Object> values) {
jtulach@934
   168
        Object json = createObj();
jaroslav@371
   169
        for (Map.Entry<String, Object> entry : values.entrySet()) {
jtulach@934
   170
            putObj(json, entry.getKey(), entry.getValue());
jaroslav@371
   171
        }
jaroslav@371
   172
        return json;
jaroslav@371
   173
    }
jtulach@934
   174
    
jtulach@934
   175
    @JavaScriptBody(args = {  }, body = "return {};")
jtulach@934
   176
    private static native Object createObj();
jtulach@934
   177
    @JavaScriptBody(args = { "obj", "prop", "val" }, body = "obj[prop] = val;")
jtulach@934
   178
    private static native void putObj(Object obj, String prop, Object val);
jaroslav@371
   179
jaroslav@371
   180
    @Override
jaroslav@371
   181
    @JavaScriptBody(args = { "s", "args" }, body = ""
jaroslav@371
   182
        + "var f = new Function(s); "
jaroslav@371
   183
        + "return f.apply(null, args);"
jaroslav@371
   184
    )
jaroslav@371
   185
    public native Object executeScript(String script, Object[] arguments);
jaroslav@371
   186
jaroslav@371
   187
    @JavaScriptBody(args = {  }, body = 
jaroslav@371
   188
          "var h;"
jaroslav@371
   189
        + "if (!!window && !!window.location && !!window.location.href)\n"
jaroslav@371
   190
        + "  h = window.location.href;\n"
jaroslav@371
   191
        + "else "
jaroslav@371
   192
        + "  h = null;"
jaroslav@371
   193
        + "return h;\n"
jaroslav@371
   194
    )
jaroslav@371
   195
    private static native String findBaseURL();
jaroslav@371
   196
    
jaroslav@371
   197
    @Override
jaroslav@371
   198
    public URI prepareURL(String content, String mimeType, String[] parameters) {
jaroslav@371
   199
        try {
jaroslav@371
   200
            final URL baseURL = new URL(findBaseURL());
jaroslav@371
   201
            StringBuilder sb = new StringBuilder();
jaroslav@371
   202
            sb.append("/dynamic?mimeType=").append(mimeType);
jaroslav@371
   203
            for (int i = 0; i < parameters.length; i++) {
jaroslav@371
   204
                sb.append("&param" + i).append("=").append(parameters[i]);
jaroslav@371
   205
            }
jaroslav@371
   206
            String mangle = content.replace("\n", "%0a")
jaroslav@371
   207
                .replace("\"", "\\\"").replace(" ", "%20");
jaroslav@371
   208
            sb.append("&content=").append(mangle);
jaroslav@371
   209
jaroslav@371
   210
            URL query = new URL(baseURL, sb.toString());
jaroslav@371
   211
            URLConnection c = query.openConnection();
jaroslav@371
   212
            BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
jaroslav@371
   213
            URI connectTo = new URI(br.readLine());
jaroslav@371
   214
            return connectTo;
jaroslav@371
   215
        } catch (IOException ex) {
jaroslav@371
   216
            throw new IllegalStateException(ex);
jaroslav@371
   217
        } catch (URISyntaxException ex) {
jaroslav@371
   218
            throw new IllegalStateException(ex);
jaroslav@371
   219
        }
jaroslav@371
   220
    }
jaroslav@371
   221
jaroslav@371
   222
    @Override
jaroslav@371
   223
    public boolean canFailWebSocketTest() {
jtulach@623
   224
        return true;
jaroslav@371
   225
    }
jaroslav@391
   226
jtulach@771
   227
    private static final class AllBundlesLoader extends ClassLoader {
jtulach@771
   228
        private final Bundle[] arr;
jtulach@771
   229
jtulach@771
   230
        public AllBundlesLoader(Bundle[] arr) {
jtulach@771
   231
            super(ClassLoader.getSystemClassLoader().getParent());
jtulach@771
   232
            this.arr = arr;
jtulach@771
   233
        }
jtulach@771
   234
jtulach@771
   235
        @Override
jtulach@771
   236
        public Class<?> loadClass(String name) throws ClassNotFoundException {
jtulach@771
   237
            return loadClass(name, false);
jtulach@771
   238
        }
jtulach@771
   239
jtulach@771
   240
        @Override
jtulach@771
   241
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
jtulach@771
   242
            ClassNotFoundException err = null;
jtulach@771
   243
            for (Bundle b : arr) {
jtulach@771
   244
                try {
jtulach@771
   245
                    Class<?> cls = b.loadClass(name);
jtulach@771
   246
                    if (FrameworkUtil.getBundle(cls) == b) {
jtulach@771
   247
                        return cls;
jtulach@771
   248
                    }
jtulach@771
   249
                } catch (ClassNotFoundException ex) {
jtulach@771
   250
                    err = ex;
jtulach@771
   251
                }
jtulach@771
   252
            }
jtulach@771
   253
            throw err;
jtulach@771
   254
        }
jtulach@771
   255
jtulach@771
   256
        @Override
jtulach@771
   257
        protected URL findResource(String name) {
jtulach@771
   258
            for (Bundle b : arr) {
jtulach@771
   259
                URL r = b.getResource(name);
jtulach@771
   260
                if (r != null) {
jtulach@771
   261
                    return r;
jtulach@771
   262
                }
jtulach@771
   263
            }
jtulach@771
   264
            return null;
jtulach@771
   265
        }
jtulach@771
   266
jtulach@771
   267
        @Override
jtulach@771
   268
        protected Enumeration<URL> findResources(String name) throws IOException {
jtulach@771
   269
            List<URL> ret = new ArrayList<URL>();
jtulach@771
   270
            for (Bundle b : arr) {
jtulach@771
   271
                Enumeration<URL> en = b.getResources(name);
jtulach@771
   272
                if (en != null) while (en.hasMoreElements()) {
jtulach@771
   273
                    URL u = en.nextElement();
jtulach@771
   274
                    ret.add(u);
jtulach@771
   275
                }
jtulach@771
   276
            }
jtulach@771
   277
            return Collections.enumeration(ret);
jtulach@771
   278
        }
jtulach@771
   279
        
jtulach@771
   280
        
jtulach@771
   281
        
jtulach@771
   282
    }
jaroslav@370
   283
}