javaquery/api/src/test/java/org/apidesign/bck2brwsr/htmlpage/JSONTest.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 10 Apr 2013 11:43:46 +0200
branchmodel
changeset 963 62d77cc38117
parent 960 4887e22cb810
child 1009 80c46ea076d3
child 1012 b22c86471837
permissions -rw-r--r--
Clean up script elements after JSONP callback
     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.Arrays;
    21 import java.util.Iterator;
    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 = PersonImpl.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 native int scriptElements();
   215 
   216     @Http(@Http.Resource(
   217         content = "{'firstName': 'Sitar', 'sex': 'MALE'}", 
   218         path="/person.json", 
   219         mimeType = "application/json"
   220     ))
   221     @BrwsrTest public void loadAndParseJSONSentToArray() throws InterruptedException {
   222         if (js == null) {
   223             js = new JSONik();
   224             js.applyBindings();
   225 
   226             js.fetchArray("person.json");
   227         }
   228         
   229         Person p = js.getFetched();
   230         if (p == null) {
   231             throw new InterruptedException();
   232         }
   233         
   234         assert p != null : "We should get our person back: " + p;
   235         assert "Sitar".equals(p.getFirstName()) : "Expecting Sitar: " + p.getFirstName();
   236         assert Sex.MALE.equals(p.getSex()) : "Expecting MALE: " + p.getSex();
   237     }
   238     
   239     @Http(@Http.Resource(
   240         content = "[{'firstName': 'Gitar', 'sex': 'FEMALE'}]", 
   241         path="/person.json", 
   242         mimeType = "application/json"
   243     ))
   244     @BrwsrTest public void loadAndParseJSONArraySingle() throws InterruptedException {
   245         if (js == null) {
   246             js = new JSONik();
   247             js.applyBindings();
   248         
   249             js.fetch("person.json");
   250         }
   251         
   252         Person p = js.getFetched();
   253         if (p == null) {
   254             throw new InterruptedException();
   255         }
   256         
   257         assert p != null : "We should get our person back: " + p;
   258         assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName();
   259         assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
   260     }
   261     
   262     @Http(@Http.Resource(
   263         content = "{'info':[{'firstName': 'Gitar', 'sex': 'FEMALE'}]}", 
   264         path="/people.json", 
   265         mimeType = "application/json"
   266     ))
   267     @BrwsrTest public void loadAndParseArrayInPeople() throws InterruptedException {
   268         if (js == null) {
   269             js = new JSONik();
   270             js.applyBindings();
   271         
   272             js.fetchPeople("people.json");
   273         }
   274         
   275         if (0 == js.getFetchedCount()) {
   276             throw new InterruptedException();
   277         }
   278 
   279         assert js.getFetchedCount() == 1 : "One person loaded: " + js.getFetchedCount();
   280         
   281         Person p = js.getFetched();
   282         
   283         assert p != null : "We should get our person back: " + p;
   284         assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName();
   285         assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
   286     }
   287     
   288     @Http(@Http.Resource(
   289         content = "{'age':[1, 2, 3]}", 
   290         path="/people.json", 
   291         mimeType = "application/json"
   292     ))
   293     @BrwsrTest public void loadAndParseArrayOfIntegers() throws InterruptedException {
   294         if (js == null) {
   295             js = new JSONik();
   296             js.applyBindings();
   297         
   298             js.fetchPeopleAge("people.json");
   299         }
   300         
   301         if (0 == js.getFetchedCount()) {
   302             throw new InterruptedException();
   303         }
   304 
   305         assert js.getFetchedCount() == 6 : "1 + 2 + 3 is " + js.getFetchedCount();
   306     }
   307     
   308     @OnReceive(url="/{url}")
   309     static void fetchPeopleSex(People p, JSONik model) {
   310         model.setFetchedCount(1);
   311         model.getFetchedSex().addAll(p.getSex());
   312     }
   313     
   314     
   315     @Http(@Http.Resource(
   316         content = "{'sex':['FEMALE', 'MALE', 'MALE']}", 
   317         path="/people.json", 
   318         mimeType = "application/json"
   319     ))
   320     @BrwsrTest public void loadAndParseArrayOfEnums() throws InterruptedException {
   321         if (js == null) {
   322             js = new JSONik();
   323             js.applyBindings();
   324         
   325             js.fetchPeopleSex("people.json");
   326         }
   327         
   328         if (0 == js.getFetchedCount()) {
   329             throw new InterruptedException();
   330         }
   331 
   332         assert js.getFetchedCount() == 1 : "Loaded";
   333         
   334         assert js.getFetchedSex().size() == 3 : "Three values " + js.getFetchedSex();
   335         assert js.getFetchedSex().get(0) == Sex.FEMALE : "Female first " + js.getFetchedSex();
   336         assert js.getFetchedSex().get(1) == Sex.MALE : "male 2nd " + js.getFetchedSex();
   337         assert js.getFetchedSex().get(2) == Sex.MALE : "male 3rd " + js.getFetchedSex();
   338     }
   339     
   340     @Http(@Http.Resource(
   341         content = "[{'firstName': 'Gitar', 'sex': 'FEMALE'},"
   342         + "{'firstName': 'Peter', 'sex': 'MALE'}"
   343         + "]", 
   344         path="/person.json", 
   345         mimeType = "application/json"
   346     ))
   347     @BrwsrTest public void loadAndParseJSONArray() throws InterruptedException {
   348         if (js == null) {
   349             js = new JSONik();
   350             js.applyBindings();
   351             js.fetchArray("person.json");
   352         }
   353         
   354         
   355         Person p = js.getFetched();
   356         if (p == null) {
   357             throw new InterruptedException();
   358         }
   359         
   360         assert js.getFetchedCount() == 2 : "We got two values: " + js.getFetchedCount();
   361         assert p != null : "We should get our person back: " + p;
   362         assert "Gitar".equals(p.getFirstName()) : "Expecting Gitar: " + p.getFirstName();
   363         assert Sex.FEMALE.equals(p.getSex()) : "Expecting FEMALE: " + p.getSex();
   364     }
   365 
   366     @Factory public static Object[] create() {
   367         return VMTest.create(JSONTest.class);
   368     }
   369     
   370 }