xhr4j/src/test/java/org/netbeans/html/xhr4j/JsonKnockoutTest.java
author Jaroslav Tulach <jtulach@netbeans.org>
Mon, 29 Feb 2016 05:25:31 +0100
branchxhr4j
changeset 1057 b547f8f663f5
parent 838 ko-ws-tyrus/src/test/java/org/netbeans/html/wstyrus/TyrusKnockoutTest.java@bdc3d696dd4a
permissions -rw-r--r--
#257849: xhr4j module uses java.net package to handle @OnReceive requests to workaround CORS limitations
     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.xhr4j;
    44 
    45 import java.io.BufferedReader;
    46 import java.io.IOException;
    47 import java.io.InputStreamReader;
    48 import java.lang.annotation.Annotation;
    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.List;
    56 import java.util.Map;
    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.tck.KOTest;
    66 import org.netbeans.html.json.tck.KnockoutTCK;
    67 import org.netbeans.html.ko4j.KO4J;
    68 import org.openide.util.lookup.ServiceProvider;
    69 import org.testng.Assert;
    70 import static org.testng.Assert.*;
    71 import org.testng.annotations.Factory;
    72 
    73 /**
    74  *
    75  * @author Jaroslav Tulach
    76  */
    77 @ServiceProvider(service = KnockoutTCK.class)
    78 public final class JsonKnockoutTest extends KnockoutTCK {
    79     private static Class<?> browserClass;
    80     private static Fn.Presenter browserContext;
    81     
    82     public JsonKnockoutTest() {
    83     }
    84     
    85     @Factory public static Object[] compatibilityTests() throws Exception {
    86         Class[] arr = testClasses();
    87         for (int i = 0; i < arr.length; i++) {
    88             assertEquals(arr[i].getClassLoader(),
    89                 JsonKnockoutTest.class.getClassLoader(),
    90                 "All classes loaded by the same classloader"
    91             );
    92         }
    93         
    94         URI uri = JsonDynamicHTTP.initServer();
    95     
    96         final BrowserBuilder bb = BrowserBuilder.newBrowser().loadClass(JsonKnockoutTest.class).
    97             loadPage(uri.toString()).
    98             invoke("initialized");
    99         
   100         Executors.newSingleThreadExecutor().submit(new Runnable() {
   101             @Override
   102             public void run() {
   103                 bb.showAndWait();
   104             }
   105         });
   106         
   107         ClassLoader l = getClassLoader();
   108         List<Object> res = new ArrayList<Object>();
   109         for (int i = 0; i < arr.length; i++) {
   110             Class<?> c = Class.forName(arr[i].getName(), true, l);
   111             Class<? extends Annotation> koTest = 
   112                 c.getClassLoader().loadClass(KOTest.class.getName()).
   113                 asSubclass(Annotation.class);
   114             for (Method m : c.getMethods()) {
   115                 if (m.getAnnotation(koTest) != null) {
   116                     res.add(new JsonFX(browserContext, m));
   117                 }
   118             }
   119         }
   120         return res.toArray();
   121     }
   122 
   123     static synchronized ClassLoader getClassLoader() throws InterruptedException {
   124         while (browserClass == null) {
   125             JsonKnockoutTest.class.wait();
   126         }
   127         return browserClass.getClassLoader();
   128     }
   129     
   130     public static synchronized void initialized(Class<?> browserCls) throws Exception {
   131         browserClass = browserCls;
   132         browserContext = Fn.activePresenter();
   133         JsonKnockoutTest.class.notifyAll();
   134     }
   135     
   136     public static void initialized() throws Exception {
   137         Assert.assertSame(JsonKnockoutTest.class.getClassLoader(),
   138             ClassLoader.getSystemClassLoader(),
   139             "No special classloaders"
   140         );
   141         JsonKnockoutTest.initialized(JsonKnockoutTest.class);
   142     }
   143 
   144     @Override
   145     public boolean canFailWebSocketTest() {
   146         return true;
   147     }
   148     
   149     @Override
   150     public BrwsrCtx createContext() {
   151         KO4J ko = new KO4J(browserContext);
   152         XmlHttpResourceContext tc = new XmlHttpResourceContext();
   153         Contexts.Builder cb = Contexts.newBuilder().
   154             register(Technology.class, ko.knockout(), 10).
   155             register(Executor.class, (Executor)browserContext, 10).
   156             register(Fn.Presenter.class, (Fn.Presenter)browserContext, 10);
   157         tc.fillContext(cb, browserClass);
   158         return cb.build();
   159     }
   160 
   161     @Override
   162     public Object createJSON(Map<String, Object> values) {
   163         Object json = createJSON();
   164         for (Map.Entry<String, Object> entry : values.entrySet()) {
   165             setProperty(json, entry.getKey(), entry.getValue());
   166         }
   167         return json;
   168     }
   169 
   170     @JavaScriptBody(args = {}, body = "return new Object();")
   171     private static native Object createJSON();
   172 
   173     @JavaScriptBody(args = {"json", "key", "value"}, body = "json[key] = value;")
   174     private static native void setProperty(Object json, String key, Object value);
   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 }