javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/JSONTest.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 18 Apr 2013 17:18:10 +0200
branchfx
changeset 1013 32502264b896
parent 1012 b22c86471837
permissions -rw-r--r--
scriptElements - another native method
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.htmlpage;
    19 
    20 import java.util.Iterator;
    21 import javafx.scene.web.WebEngine;
    22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    23 import org.apidesign.bck2brwsr.htmlpage.api.OnReceive;
    24 import org.apidesign.bck2brwsr.htmlpage.api.Page;
    25 import org.apidesign.bck2brwsr.htmlpage.api.Property;
    26 import org.apidesign.bck2brwsr.vmtest.BrwsrTest;
    27 import org.apidesign.bck2brwsr.vmtest.Http;
    28 import org.apidesign.bck2brwsr.vmtest.VMTest;
    29 import org.json.JSONException;
    30 import org.json.JSONObject;
    31 import org.json.JSONTokener;
    32 import org.testng.annotations.Test;
    33 import static org.testng.Assert.*;
    34 import org.testng.annotations.Factory;
    35 
    36 /** Need to verify that models produce reasonable JSON objects.
    37  *
    38  * @author Jaroslav Tulach <jtulach@netbeans.org>
    39  */
    40 @Page(xhtml = "Empty.html", className = "JSONik", properties = {
    41     @Property(name = "fetched", type = Person.class),
    42     @Property(name = "fetchedCount", type = int.class),
    43     @Property(name = "fetchedSex", type = Sex.class, array = true)
    44 })
    45 public class JSONTest {
    46     private JSONik js;
    47     private Integer orig;
    48     
    49     @Test public void personToString() throws JSONException {
    50         Person p = new Person();
    51         p.setSex(Sex.MALE);
    52         p.setFirstName("Jarda");
    53         p.setLastName("Tulach");
    54         
    55         JSONTokener t = new JSONTokener(p.toString());
    56         JSONObject o;
    57         try {
    58             o = new JSONObject(t);
    59         } catch (JSONException ex) {
    60             throw new AssertionError("Can't parse " + p.toString(), ex);
    61         }
    62         
    63         Iterator it = o.sortedKeys();
    64         assertEquals(it.next(), "firstName");
    65         assertEquals(it.next(), "lastName");
    66         assertEquals(it.next(), "sex");
    67         
    68         assertEquals(o.getString("firstName"), "Jarda");
    69         assertEquals(o.getString("lastName"), "Tulach");
    70         assertEquals(o.getString("sex"), "MALE");
    71     }
    72     
    73     @Test public void personWithWildCharactersAndNulls() throws JSONException {
    74         Person p = new Person();
    75         p.setFirstName("'\"\n");
    76         p.setLastName("\t\r\u0002");
    77         
    78         JSONTokener t = new JSONTokener(p.toString());
    79         JSONObject o;
    80         try {
    81             o = new JSONObject(t);
    82         } catch (JSONException ex) {
    83             throw new AssertionError("Can't parse " + p.toString(), ex);
    84         }
    85         
    86         Iterator it = o.sortedKeys();
    87         assertEquals(it.next(), "firstName");
    88         assertEquals(it.next(), "lastName");
    89         assertEquals(it.next(), "sex");
    90         
    91         assertEquals(o.getString("firstName"), p.getFirstName());
    92         assertEquals(o.getString("lastName"), p.getLastName());
    93         assertEquals(o.get("sex"), JSONObject.NULL);
    94     }
    95     
    96     @Test public void personsInArray() throws JSONException {
    97         Person p1 = new Person();
    98         p1.setFirstName("One");
    99 
   100         Person p2 = new Person();
   101         p2.setFirstName("Two");
   102         
   103         People arr = new People();
   104         arr.getInfo().add(p1);
   105         arr.getInfo().add(p2);
   106         arr.getNicknames().add("Prvn\u00ed k\u016f\u0148");
   107         final String n2 = "Druh\u00fd hlem\u00fd\u017e\u010f, star\u0161\u00ed";
   108         arr.getNicknames().add(n2);
   109         arr.getAge().add(33);
   110         arr.getAge().add(73);
   111         
   112         
   113         final String json = arr.toString();
   114         
   115         JSONTokener t = new JSONTokener(json);
   116         JSONObject o;
   117         try {
   118             o = new JSONObject(t);
   119         } catch (JSONException ex) {
   120             throw new AssertionError("Can't parse " + json, ex);
   121         }
   122 
   123         assertEquals(o.getJSONArray("info").getJSONObject(0).getString("firstName"), "One");
   124         assertEquals(o.getJSONArray("nicknames").getString(1), n2);
   125         assertEquals(o.getJSONArray("age").getInt(1), 73);
   126     }
   127     
   128     
   129     @OnReceive(url="/{url}")
   130     static void fetch(Person p, JSONik model) {
   131         model.setFetched(p);
   132     }
   133 
   134     @OnReceive(url="/{url}")
   135     static void fetchArray(Person[] p, JSONik model) {
   136         model.setFetchedCount(p.length);
   137         model.setFetched(p[0]);
   138     }
   139     
   140     @OnReceive(url="/{url}")
   141     static void fetchPeople(People p, JSONik model) {
   142         model.setFetchedCount(p.getInfo().size());
   143         model.setFetched(p.getInfo().get(0));
   144     }
   145 
   146     @OnReceive(url="/{url}")
   147     static void fetchPeopleAge(People p, JSONik model) {
   148         int sum = 0;
   149         for (int a : p.getAge()) {
   150             sum += a;
   151         }
   152         model.setFetchedCount(sum);
   153     }
   154     
   155     @Http(@Http.Resource(
   156         content = "{'firstName': 'Sitar', 'sex': 'MALE'}", 
   157         path="/person.json", 
   158         mimeType = "application/json"
   159     ))
   160     @BrwsrTest public void loadAndParseJSON() throws InterruptedException {
   161         if (js == null) {
   162             js = new JSONik();
   163             js.applyBindings();
   164 
   165             js.fetch("person.json");
   166         }
   167     
   168         Person p = js.getFetched();
   169         if (p == null) {
   170             throw new InterruptedException();
   171         }
   172         
   173         assert "Sitar".equals(p.getFirstName()) : "Expecting Sitar: " + p.getFirstName();
   174         assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex();
   175     }
   176     
   177     @OnReceive(url="/{url}?callme={me}", jsonp = "me")
   178     static void fetchViaJSONP(Person p, JSONik model) {
   179         model.setFetched(p);
   180     }
   181     
   182     @Http(@Http.Resource(
   183         content = "$0({'firstName': 'Mitar', 'sex': 'MALE'})", 
   184         path="/person.json", 
   185         mimeType = "application/javascript",
   186         parameters = { "callme" }
   187     ))
   188     @BrwsrTest public void loadAndParseJSONP() throws InterruptedException {
   189         
   190         if (js == null) {
   191             orig = scriptElements();
   192             assert orig > 0 : "There should be some scripts on the page";
   193             
   194             js = new JSONik();
   195             js.applyBindings();
   196 
   197             js.fetchViaJSONP("person.json");
   198         }
   199     
   200         Person p = js.getFetched();
   201         if (p == null) {
   202             throw new InterruptedException();
   203         }
   204         
   205         assert "Mitar".equals(p.getFirstName()) : "Unexpected: " + p.getFirstName();
   206         assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex();
   207         
   208         int now = scriptElements();
   209         
   210         assert orig == now : "The set of elements is unchanged. Delta: " + (now - orig);
   211     }
   212     
   213     @JavaScriptBody(args = {  }, body = "return window.document.getElementsByTagName('script').length;")
   214     private static int scriptElements() {
   215         WebEngine eng = (WebEngine) System.getProperties().get("webEngine");
   216         return (Integer) eng.executeScript(
   217             "window.document.getElementsByTagName('script').length"
   218         );
   219     }
   220 
   221     @Http(@Http.Resource(
   222         content = "{'firstName': 'Sitar', 'sex': 'MALE'}", 
   223         path="/person.json", 
   224         mimeType = "application/json"
   225     ))
   226     @BrwsrTest public void loadAndParseJSONSentToArray() throws InterruptedException {
   227         if (js == null) {
   228             js = new JSONik();
   229             js.applyBindings();
   230 
   231             js.fetchArray("person.json");
   232         }
   233         
   234         Person p = js.getFetched();
   235         if (p == null) {
   236             throw new InterruptedException();
   237         }
   238         
   239         assert p != null : "We should get our person back: " + p;
   240         assert "Sitar".equals(p.getFirstName()) : "Expecting Sitar: " + p.getFirstName();
   241         assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex();
   242     }
   243     
   244     @Http(@Http.Resource(
   245         content = "[{'firstName': 'Gitar', 'sex': 'FEMALE'}]", 
   246         path="/person.json", 
   247         mimeType = "application/json"
   248     ))
   249     @BrwsrTest public void loadAndParseJSONArraySingle() throws InterruptedException {
   250         if (js == null) {
   251             js = new JSONik();
   252             js.applyBindings();
   253         
   254             js.fetch("person.json");
   255         }
   256         
   257         Person p = js.getFetched();
   258         if (p == null) {
   259             throw new InterruptedException();
   260         }
   261         
   262         assert p != null : "We should get our person back: " + p;
   263         assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName();
   264         assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
   265     }
   266     
   267     @Http(@Http.Resource(
   268         content = "{'info':[{'firstName': 'Gitar', 'sex': 'FEMALE'}]}", 
   269         path="/people.json", 
   270         mimeType = "application/json"
   271     ))
   272     @BrwsrTest public void loadAndParseArrayInPeople() throws InterruptedException {
   273         if (js == null) {
   274             js = new JSONik();
   275             js.applyBindings();
   276         
   277             js.fetchPeople("people.json");
   278         }
   279         
   280         if (0 == js.getFetchedCount()) {
   281             throw new InterruptedException();
   282         }
   283 
   284         assert js.getFetchedCount() == 1 : "One person loaded: " + js.getFetchedCount();
   285         
   286         Person p = js.getFetched();
   287         
   288         assert p != null : "We should get our person back: " + p;
   289         assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName();
   290         assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
   291     }
   292     
   293     @Http(@Http.Resource(
   294         content = "{'age':[1, 2, 3]}", 
   295         path="/people.json", 
   296         mimeType = "application/json"
   297     ))
   298     @BrwsrTest public void loadAndParseArrayOfIntegers() throws InterruptedException {
   299         if (js == null) {
   300             js = new JSONik();
   301             js.applyBindings();
   302         
   303             js.fetchPeopleAge("people.json");
   304         }
   305         
   306         if (0 == js.getFetchedCount()) {
   307             throw new InterruptedException();
   308         }
   309 
   310         assert js.getFetchedCount() == 6 : "1 + 2 + 3 is " + js.getFetchedCount();
   311     }
   312     
   313     @OnReceive(url="/{url}")
   314     static void fetchPeopleSex(People p, JSONik model) {
   315         model.setFetchedCount(1);
   316         model.getFetchedSex().addAll(p.getSex());
   317     }
   318     
   319     
   320     @Http(@Http.Resource(
   321         content = "{'sex':['FEMALE', 'MALE', 'MALE']}", 
   322         path="/people.json", 
   323         mimeType = "application/json"
   324     ))
   325     @BrwsrTest public void loadAndParseArrayOfEnums() throws InterruptedException {
   326         if (js == null) {
   327             js = new JSONik();
   328             js.applyBindings();
   329         
   330             js.fetchPeopleSex("people.json");
   331         }
   332         
   333         if (0 == js.getFetchedCount()) {
   334             throw new InterruptedException();
   335         }
   336 
   337         assert js.getFetchedCount() == 1 : "Loaded";
   338         
   339         assert js.getFetchedSex().size() == 3 : "Three values " + js.getFetchedSex();
   340         assert js.getFetchedSex().get(0) == Sex.FEMALE : "Female first " + js.getFetchedSex();
   341         assert js.getFetchedSex().get(1) == Sex.MALE : "male 2nd " + js.getFetchedSex();
   342         assert js.getFetchedSex().get(2) == Sex.MALE : "male 3rd " + js.getFetchedSex();
   343     }
   344     
   345     @Http(@Http.Resource(
   346         content = "[{'firstName': 'Gitar', 'sex': 'FEMALE'},"
   347         + "{'firstName': 'Peter', 'sex': 'MALE'}"
   348         + "]", 
   349         path="/person.json", 
   350         mimeType = "application/json"
   351     ))
   352     @BrwsrTest public void loadAndParseJSONArray() throws InterruptedException {
   353         if (js == null) {
   354             js = new JSONik();
   355             js.applyBindings();
   356             js.fetchArray("person.json");
   357         }
   358         
   359         
   360         Person p = js.getFetched();
   361         if (p == null) {
   362             throw new InterruptedException();
   363         }
   364         
   365         assert js.getFetchedCount() == 2 : "We got two values: " + js.getFetchedCount();
   366         assert p != null : "We should get our person back: " + p;
   367         assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName();
   368         assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
   369     }
   370 
   371     @Factory public static Object[] create() {
   372         return VMTest.create(JSONTest.class);
   373     }
   374     
   375 }