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