javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/ConvertTypes.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 18 Apr 2013 12:47:25 +0200
changeset 1009 80c46ea076d3
parent 963 62d77cc38117
child 1568 0db00da6f375
permissions -rw-r--r--
Test to ensure the generated JSON can really be parse by a browser
     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 org.apidesign.bck2brwsr.core.JavaScriptBody;
    21 
    22 /**
    23  *
    24  * @author Jaroslav Tulach <jtulach@netbeans.org>
    25  */
    26 public final class ConvertTypes {
    27     ConvertTypes() {
    28     }
    29     
    30     public static String toString(Object object, String property) {
    31         Object ret = getProperty(object, property);
    32         return ret == null ? null : ret.toString();
    33     }
    34 
    35     public static double toDouble(Object object, String property) {
    36         Object ret = getProperty(object, property);
    37         return ret instanceof Number ? ((Number)ret).doubleValue() : Double.NaN;
    38     }
    39 
    40     public static int toInt(Object object, String property) {
    41         Object ret = getProperty(object, property);
    42         return ret instanceof Number ? ((Number)ret).intValue() : Integer.MIN_VALUE;
    43     }
    44 
    45     public static <T> T toModel(Class<T> modelClass, Object object, String property) {
    46         Object ret = getProperty(object, property);
    47         if (ret == null || modelClass.isInstance(ret)) {
    48             return modelClass.cast(ret);
    49         }
    50         throw new IllegalStateException("Value " + ret + " is not of type " + modelClass);
    51     }
    52     
    53     public static String toJSON(Object value) {
    54         if (value == null) {
    55             return "null";
    56         }
    57         if (value instanceof Enum) {
    58             value = value.toString();
    59         }
    60         if (value instanceof String) {
    61             return '"' + 
    62                 ((String)value).
    63                     replace("\"", "\\\"").
    64                     replace("\n", "\\n").
    65                     replace("\r", "\\r").
    66                     replace("\t", "\\t")
    67                 + '"';
    68         }
    69         return value.toString();
    70     }
    71     
    72     @JavaScriptBody(args = { "object", "property" },
    73         body = "if (property === null) return object;\n"
    74         + "var p = object[property]; return p ? p : null;"
    75     )
    76     private static Object getProperty(Object object, String property) {
    77         return null;
    78     }
    79     
    80     public static String createJSONP(Object[] jsonResult, Runnable whenDone) {
    81         int h = whenDone.hashCode();
    82         String name;
    83         for (;;) {
    84             name = "jsonp" + Integer.toHexString(h);
    85             if (defineIfUnused(name, jsonResult, whenDone)) {
    86                 return name;
    87             }
    88             h++;
    89         }
    90     }
    91 
    92     @JavaScriptBody(args = { "name", "arr", "run" }, body = 
    93         "if (window[name]) return false;\n "
    94       + "window[name] = function(data) {\n "
    95       + "  delete window[name];\n"
    96       + "  var el = window.document.getElementById(name);\n"
    97       + "  el.parentNode.removeChild(el);\n"
    98       + "  arr[0] = data;\n"
    99       + "  run.run__V();\n"
   100       + "};\n"
   101       + "return true;\n"
   102     )
   103     private static boolean defineIfUnused(String name, Object[] arr, Runnable run) {
   104         return true;
   105     }
   106     
   107     @JavaScriptBody(args = { "url", "arr", "callback" }, body = ""
   108         + "var request = new XMLHttpRequest();\n"
   109         + "request.open('GET', url, true);\n"
   110         + "request.setRequestHeader('Content-Type', 'application/json; charset=utf-8');\n"
   111         + "request.onreadystatechange = function() {\n"
   112         + "  if (this.readyState!==4) return;\n"
   113         + "  try {\n"
   114         + "    arr[0] = eval('(' + this.response + ')');\n"
   115         + "  } catch (error) {;\n"
   116         + "    throw 'Cannot parse' + error + ':' + this.response;\n"
   117         + "  };\n"
   118         + "  callback.run__V();\n"
   119         + "};"
   120         + "request.send();"
   121     )
   122     private static void loadJSON(
   123         String url, Object[] jsonResult, Runnable whenDone
   124     ) {
   125     }
   126     
   127     public static void loadJSON(
   128         String url, Object[] jsonResult, Runnable whenDone, String jsonp
   129     ) {
   130         if (jsonp == null) {
   131             loadJSON(url, jsonResult, whenDone);
   132         } else {
   133             loadJSONP(url, jsonp);
   134         }
   135     }
   136     
   137     @JavaScriptBody(args = { "url", "jsonp" }, body = 
   138         "var scrpt = window.document.createElement('script');\n "
   139         + "scrpt.setAttribute('src', url);\n "
   140         + "scrpt.setAttribute('id', jsonp);\n "
   141         + "scrpt.setAttribute('type', 'text/javascript');\n "
   142         + "var body = document.getElementsByTagName('body')[0];\n "
   143         + "body.appendChild(scrpt);\n"
   144     )
   145     private static void loadJSONP(String url, String jsonp) {
   146         
   147     }
   148     
   149     public static void extractJSON(Object jsonObject, String[] props, Object[] values) {
   150         for (int i = 0; i < props.length; i++) {
   151             values[i] = getProperty(jsonObject, props[i]);
   152         }
   153     }
   154     
   155 }