Example usage for com.google.gwt.json.client JSONValue isObject

List of usage examples for com.google.gwt.json.client JSONValue isObject

Introduction

In this page you can find the example usage for com.google.gwt.json.client JSONValue isObject.

Prototype

public JSONObject isObject() 

Source Link

Document

Returns non-null if this JSONValue is really a JSONObject.

Usage

From source file:lh.api.showcase.client.referencedata.cities.CitiesResponseJsonParser.java

License:Apache License

private City getCityInfo(JSONObject jsCityObj) {
    JSONValue jsCityCodeVal = jsCityObj.get("CityCode");
    JSONValue jsCountryCodeVal = jsCityObj.get("CountryCode");

    if (jsCityCodeVal == null || jsCountryCodeVal == null) {
        return null;
    }/*from  w  ww  . j  a v a 2s  .  c om*/
    JSONString jsCityCodeStr = jsCityCodeVal.isString();
    JSONString jsCountryCodeStr = jsCountryCodeVal.isString();

    JSONNumber jsLatitudeNum = null;
    JSONNumber jsLongitudeNum = null;
    JSONValue jsCoordinateVal = jsCityObj.get("Position");
    if (jsCoordinateVal != null) {
        JSONObject jsCoordinateObj = jsCoordinateVal.isObject().get("Coordinate").isObject();
        jsLatitudeNum = jsCoordinateObj.get("Latitude").isNumber();
        jsLongitudeNum = jsCoordinateObj.get("Longitude").isNumber();
    }

    JSONObject jsNamesObj = jsCityObj.get("Names").isObject();

    JSONValue jsAirportsVal = jsCityObj.get("Airports");
    JSONObject jsAirportsObj = (jsAirportsVal == null) ? (null) : (jsAirportsVal.isObject());

    return new City((jsCityCodeStr == null) ? ("") : (jsCityCodeStr.toString().replace("\"", "")),
            (jsCountryCodeStr == null) ? ("") : (jsCountryCodeStr.toString().replace("\"", "")),
            (jsLatitudeNum == null) ? (null) : (jsLatitudeNum.doubleValue()),
            (jsLongitudeNum == null) ? (null) : (jsLongitudeNum.doubleValue()), getAirportInfo(jsAirportsObj),
            JsonParserUtils.getNamesMap(jsNamesObj));
}

From source file:lh.api.showcase.client.referencedata.countries.CountriesResponseJsonParser.java

License:Apache License

@Override
public List<Country> parse(String json) {
    List<Country> countries = new ArrayList<Country>();

    logger.log(Level.INFO, "JSON parsing");
    JSONValue jsv = JSONParser.parseStrict(json);
    JSONObject jobj = jsv.isObject();

    JSONValue jsCountriesResourceVal = jobj.get("CountryResource");
    JSONObject jsCountriesResourceObj = jsCountriesResourceVal.isObject();

    JSONValue jsCountriesVal = jsCountriesResourceObj.get("Countries");
    JSONObject jsCountriesObj = jsCountriesVal.isObject();

    JSONValue jsCountryVal = jsCountriesObj.get("Country");
    JSONObject jsCountryObj = jsCountryVal.isObject();

    if (jsCountryObj == null) {
        JSONArray jarrayCountries = jsCountryVal.isArray();
        if (jarrayCountries != null) {
            for (int i = 0; i < jarrayCountries.size(); ++i) {

                JSONObject jsCountryObject = jarrayCountries.get(i).isObject();
                if (jsCountryObject == null) {
                    continue;
                }/*from w w w  .j a va2 s .  c  om*/
                getCountryInfo(jsCountryObject, countries);
            }
        }
    } else {
        getCountryInfo(jsCountryObj, countries);
    }
    return countries;
}

From source file:lh.api.showcase.client.referencedata.countries.CountriesResponseJsonParser.java

License:Apache License

private void getCountryInfo(JSONObject jsCountryObj, List<Country> countries) {
    JSONValue jsCountryCodeVal = jsCountryObj.get("CountryCode");
    JSONString jsCountryCodeStr = (jsCountryCodeVal == null) ? (null) : (jsCountryCodeVal.isString());

    JSONValue jsCountryZoneVal = jsCountryObj.get("ZoneCode");
    JSONString jsZoneCodeStr = (jsCountryZoneVal == null) ? (null) : (jsCountryZoneVal.isString());

    JSONValue jsNamesVal = jsCountryObj.get("Names");
    JSONObject jsNamesObj = jsNamesVal.isObject();

    countries.add(/*from  ww w.j  a  v a2  s  . c  om*/
            new Country((jsCountryCodeStr == null) ? ("") : (jsCountryCodeStr.toString().replace("\"", "")),
                    (jsZoneCodeStr == null) ? ("") : (jsZoneCodeStr.toString().replace("\"", "")),
                    JsonParserUtils.getNamesMap(jsNamesObj)));
}

From source file:lh.api.showcase.client.referencedata.nearestairports.NearestAirportsResponseJsonParser.java

License:Apache License

@Override
public List<NearestAirport> parse(String json) {

    List<NearestAirport> ret = new ArrayList<NearestAirport>();

    JSONValue jsv = JSONParser.parseStrict(json);
    JSONObject jobj = jsv.isObject();

    JSONValue jsAirportResourceVal = jobj.get("NearestAirportResource");
    JSONObject jsAirportResourceObj = jsAirportResourceVal.isObject();

    JSONValue jsAirportsVal = jsAirportResourceObj.get("Airports");
    JSONObject jsAirportsObj = jsAirportsVal.isObject();

    JSONValue jsAirportVal = jsAirportsObj.get("Airport");
    JSONObject jsAirportObj = jsAirportVal.isObject();

    if (jsAirportObj == null) {
        JSONArray jarrayAirports = jsAirportVal.isArray();
        if (jarrayAirports != null) {
            for (int i = 0; i < jarrayAirports.size(); ++i) {
                JSONObject jsAirportObject = jarrayAirports.get(i).isObject();
                if (jsAirportObject == null) {
                    continue;
                }//from w  ww  .  j  a  va2 s .  c om
                NearestAirport na = getNearestAirportInfo(jsAirportObject);
                if (na != null) {
                    ret.add(na);
                }
            }
        }
    } else {
        NearestAirport na = getNearestAirportInfo(jsAirportObj);
        if (na != null) {
            ret.add(na);
        }
    }
    return ret;
}

From source file:MY_PACKAGE.client.Index.java

License:Apache License

/**
 * Show the successful message result of our REST call.
 * //  w  ww.j  a v a2  s.  c om
 * @param val    the value containing the JSON response from the server
 */
private void showSuccessMessage(JSONValue val) {
    JSONObject obj = val.isObject();
    String name = JSONUtil.getStringValue(obj, "user");
    String browser = JSONUtil.getStringValue(obj, "userAgent");
    String server = JSONUtil.getStringValue(obj, "serverInfo");

    String message = "Hello, " + name + "!  <br/>You are using " + browser + ".<br/>The server is " + server
            + ".";
    m_longMessage.setHTML(message);
}

From source file:name.cphillipson.experimental.gwt.client.module.common.widget.suggest.MultivalueSuggestBox.java

License:Apache License

/**
 * Retrieve Options (name-value pairs) that are suggested from the REST endpoint
 * /*from  www.  ja va2  s  .  c om*/
 * @param query
 *            - the String search term
 * @param from
 *            - the 0-based begin index int
 * @param to
 *            - the end index inclusive int
 * @param callback
 *            - the OptionQueryCallback to handle the response
 */
private void queryOptions(final String query, final int from, final int to,
        final OptionQueryCallback callback) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
            URL.encode(m_restEndpointUrl + "?q=" + query + "&indexFrom=" + from + "&indexTo=" + to));

    // Set our headers
    builder.setHeader("Accept", "application/json");
    builder.setHeader("Accept-Charset", "UTF-8");

    builder.setCallback(new RequestCallback() {

        @Override
        public void onResponseReceived(com.google.gwt.http.client.Request request, Response response) {
            final JSONValue val = JSONParser.parse(response.getText());
            final JSONObject obj = val.isObject();
            final int totSize = (int) obj.get(OptionResultSet.TOTAL_SIZE).isNumber().doubleValue();
            final OptionResultSet options = new OptionResultSet(totSize);
            final JSONArray optionsArray = obj.get(OptionResultSet.OPTIONS).isArray();

            if (options.getTotalSize() > 0 && optionsArray != null) {

                for (int i = 0; i < optionsArray.size(); i++) {
                    if (optionsArray.get(i) == null) {
                        /*
                         * This happens when a JSON array has an invalid trailing comma
                         */
                        continue;
                    }

                    final JSONObject jsonOpt = optionsArray.get(i).isObject();
                    final Option option = new Option();
                    option.setName(jsonOpt.get(OptionResultSet.DISPLAY_NAME).isString().stringValue());
                    option.setValue(jsonOpt.get(OptionResultSet.VALUE).isString().stringValue());
                    options.addOption(option);
                }
            }
            callback.success(options);
        }

        @Override
        public void onError(com.google.gwt.http.client.Request request, Throwable exception) {
            callback.error(exception);
        }
    });

    try {
        builder.send();
    } catch (final RequestException e) {
        updateFormFeedback(FormFeedback.ERROR, "Error: " + e.getMessage());
    }
}

From source file:net.opentsdb.tsd.client.QueryUi.java

License:Open Source License

private void refreshVersion() {
    asyncGetJson(VERSION_URL, new GotJsonCallback() {
        public void got(final JSONValue json) {
            final JSONObject bd = json.isObject();
            final JSONString shortrev = bd.get("short_revision").isString();
            final JSONString status = bd.get("repo_status").isString();
            final JSONNumber stamp = bd.get("timestamp").isNumber();
            final JSONString user = bd.get("user").isString();
            final JSONString host = bd.get("host").isString();
            final JSONString repo = bd.get("repo").isString();
            build_data.setHTML("OpenTSDB built from revision " + shortrev.stringValue() + " in a "
                    + status.stringValue() + " state<br/>" + "Built on "
                    + new Date((long) (stamp.doubleValue() * 1000)) + " by " + user.stringValue() + '@'
                    + host.stringValue() + ':' + repo.stringValue());
        }// w  w  w  . j ava2 s  . com
    });
}

From source file:net.opentsdb.tsd.client.QueryUi.java

License:Open Source License

private void refreshGraph() {
    final Date start = start_datebox.getValue();
    if (start == null) {
        graphstatus.setText("Please specify a start time.");
        return;// w ww .  j  a  v  a2 s  . c  om
    }
    final Date end = end_datebox.getValue();
    if (end != null && !autoreoload.isChecked()) {
        if (end.getTime() <= start.getTime()) {
            end_datebox.addStyleName("dateBoxFormatError");
            graphstatus.setText("End time must be after start time!");
            return;
        }
    }
    final StringBuilder url = new StringBuilder();
    url.append("/q?start=").append(FULLDATE.format(start));
    if (end != null && !autoreoload.isChecked()) {
        url.append("&end=").append(FULLDATE.format(end));
    } else {
        // If there's no end-time, the graph may change while the URL remains
        // the same.  No browser seems to re-fetch an image once it's been
        // fetched, even if we destroy the DOM object and re-created it with the
        // same src attribute.  This has nothing to do with caching headers sent
        // by the server.  The browsers simply won't retrieve the same URL again
        // through JavaScript manipulations, period.  So as a workaround, we add
        // a special parameter that the server will delete from the query.
        url.append("&ignore=" + nrequests++);
    }
    if (!addAllMetrics(url)) {
        return;
    }
    addLabels(url);
    addFormats(url);
    addYRanges(url);
    addLogscales(url);
    if (nokey.isChecked()) {
        url.append("&nokey");
    } else if (!keypos.isEmpty() || horizontalkey.isChecked()) {
        url.append("&key=");
        if (!keypos.isEmpty()) {
            url.append(keypos);
        }
        if (horizontalkey.isChecked()) {
            url.append(" horiz");
        }
        if (keybox.isChecked()) {
            url.append(" box");
        }
    }
    url.append("&wxh=").append(wxh.getText());
    final String uri = url.toString();
    if (uri.equals(lastgraphuri)) {
        return; // Don't re-request the same graph.
    } else if (pending_requests++ > 0) {
        return;
    }
    lastgraphuri = uri;
    graphstatus.setText("Loading graph...");
    asyncGetJson(uri + "&json", new GotJsonCallback() {
        public void got(final JSONValue json) {
            if (autoreoload_timer != null) {
                autoreoload_timer.cancel();
                autoreoload_timer = null;
            }
            final JSONObject result = json.isObject();
            final JSONValue err = result.get("err");
            String msg = "";
            if (err != null) {
                displayError("An error occurred while generating the graph: " + err.isString().stringValue());
                graphstatus.setText("Please correct the error above.");
            } else {
                clearError();
                final JSONValue nplotted = result.get("plotted");
                final JSONValue cachehit = result.get("cachehit");
                if (cachehit != null) {
                    msg += "Cache hit (" + cachehit.isString().stringValue() + "). ";
                }
                if (nplotted != null && nplotted.isNumber().doubleValue() > 0) {
                    graph.setUrl(uri + "&png");
                    graph.setVisible(true);
                    msg += result.get("points").isNumber() + " points retrieved, " + nplotted
                            + " points plotted";
                } else {
                    graph.setVisible(false);
                    msg += "Your query didn't return anything";
                }
                final JSONValue timing = result.get("timing");
                if (timing != null) {
                    msg += " in " + timing + "ms.";
                } else {
                    msg += '.';
                }
            }
            final JSONValue info = result.get("info");
            if (info != null) {
                if (!msg.isEmpty()) {
                    msg += ' ';
                }
                msg += info.isString().stringValue();
            }
            graphstatus.setText(msg);
            if (result.get("etags") != null) {
                final JSONArray etags = result.get("etags").isArray();
                final int netags = etags.size();
                for (int i = 0; i < netags; i++) {
                    if (i >= metrics.getWidgetCount()) {
                        break;
                    }
                    final Widget widget = metrics.getWidget(i);
                    if (!(widget instanceof MetricForm)) {
                        break;
                    }
                    final MetricForm metric = (MetricForm) widget;
                    final JSONArray tags = etags.get(i).isArray();
                    final int ntags = tags.size();
                    for (int j = 0; j < ntags; j++) {
                        metric.autoSuggestTag(tags.get(j).isString().stringValue());
                    }
                }
            }
            if (autoreoload.isChecked()) {
                final int reload_in = Integer.parseInt(autoreoload_interval.getValue());
                if (reload_in >= 5) {
                    autoreoload_timer = new Timer() {
                        public void run() {
                            // Verify that we still want auto reload and that the graph
                            // hasn't been updated in the mean time.
                            if (autoreoload.isChecked() && lastgraphuri == uri) {
                                // Force refreshGraph to believe that we want a new graph.
                                lastgraphuri = "";
                                refreshGraph();
                            }
                        }
                    };
                    autoreoload_timer.schedule(reload_in * 1000);
                }
            }
            if (--pending_requests > 0) {
                pending_requests = 0;
                refreshGraph();
            }
        }
    });
}

From source file:net.opentsdb.tsd.client.QueryUi.java

License:Open Source License

private void asyncGetJson(final String url, final GotJsonCallback callback) {
    final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
    try {/*from w  ww.  j  a v a 2s.  c  o  m*/
        builder.sendRequest(null, new RequestCallback() {
            public void onError(final Request request, final Throwable e) {
                displayError("Failed to get " + url + ": " + e.getMessage());
                // Since we don't call the callback we've been given, reset this
                // bit of state as we're not going to retry anything right now.
                pending_requests = 0;
            }

            public void onResponseReceived(final Request request, final Response response) {
                final int code = response.getStatusCode();
                if (code == Response.SC_OK) {
                    clearError();
                    callback.got(JSONParser.parse(response.getText()));
                    return;
                } else if (code >= Response.SC_BAD_REQUEST) { // 400+ => Oops.
                    // Since we don't call the callback we've been given, reset this
                    // bit of state as we're not going to retry anything right now.
                    pending_requests = 0;
                    String err = response.getText();
                    // If the response looks like a JSON object, it probably contains
                    // an error message.
                    if (!err.isEmpty() && err.charAt(0) == '{') {
                        final JSONValue json = JSONParser.parse(err);
                        final JSONObject result = json == null ? null : json.isObject();
                        final JSONValue jerr = result == null ? null : result.get("err");
                        final JSONString serr = jerr == null ? null : jerr.isString();
                        err = serr.stringValue();
                        // If the error message has multiple lines (which is common if
                        // it contains a stack trace), show only the first line and
                        // hide the rest in a panel users can expand.
                        final int newline = err.indexOf('\n', 1);
                        final String msg = "Request failed: " + response.getStatusText();
                        if (newline < 0) {
                            displayError(msg + ": " + err);
                        } else {
                            displayError(msg);
                            final DisclosurePanel dp = new DisclosurePanel(err.substring(0, newline));
                            RootPanel.get("queryuimain").add(dp); // Attach the widget.
                            final InlineLabel content = new InlineLabel(err.substring(newline, err.length()));
                            content.addStyleName("fwf"); // For readable stack traces.
                            dp.setContent(content);
                            current_error.getElement().appendChild(dp.getElement());
                        }
                    } else {
                        displayError("Request failed while getting " + url + ": " + response.getStatusText());
                        // Since we don't call the callback we've been given, reset this
                        // bit of state as we're not going to retry anything right now.
                        pending_requests = 0;
                    }
                    graphstatus.setText("");
                }
            }
        });
    } catch (RequestException e) {
        displayError("Failed to get " + url + ": " + e.getMessage());
    }
}

From source file:net.vleu.par.gwt.client.storage.PersistentStorage.java

License:Open Source License

/**
 * Reads {@link #cookiesJson} save by {@link #writeCookies()} in the
 * browser's cookie jar/*  w  ww  . j av  a 2 s  . co m*/
 * 
 * @return The unserialized object, or null if there weren't any
 */
private JSONObject readCookies() {
    final String serializedCookies = Cookies.getCookie(COOKIE_NAME);
    JSONValue jsonValue;
    if (serializedCookies == null)
        return null;
    try {
        jsonValue = JSONParser.parseLenient(serializedCookies);
    } catch (final Exception _) {
        return null;
    }
    return jsonValue.isObject();
}