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

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

Introduction

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

Prototype

public JSONString isString() 

Source Link

Document

Returns a non-null reference if this JSONValue is really a JSONString.

Usage

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;/*from ww  w  .ja  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  w  w.  j ava  2  s . com*/
        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.opentsdb.tsd.client.RemoteOracle.java

License:Open Source License

@Override
public void requestSuggestions(final Request request, final Callback callback) {
    if (current != null) {
        pending_req = request;//w w w . j  av  a  2  s.  com
        pending_cb = callback;
        return;
    }
    current = callback;
    {
        final String this_query = request.getQuery();
        // Check if we can serve this from our local cache, without even talking
        // to the server.  This is possible if either of those is true:
        //   1. We've already seen this query recently.
        //   2. This new query precedes another one and the user basically just
        //      typed another letter, so if the new query is "less than" the last
        //      result we got from the server, we know we already cached the full
        //      range of results covering the new request.
        if ((last_query != null && last_query.compareTo(this_query) <= 0
                && this_query.compareTo(last_suggestion) < 0) || queries_seen.check(this_query)) {
            current = null;
            cache.requestSuggestions(request, callback);
            return;
        }
        last_query = this_query;
    }

    final RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,
            SUGGEST_URL + type + "&q=" + last_query);
    try {
        builder.sendRequest(null, new RequestCallback() {
            public void onError(final com.google.gwt.http.client.Request r, final Throwable e) {
                current = null; // Something bad happened, drop the current request.
                if (pending_req != null) { // But if we have another waiting...
                    requestSuggestions(pending_req, pending_cb); // ... try it now.
                }
            }

            // Need to use fully-qualified names as this class inherits already
            // from a pair of inner classes called Request / Response :-/
            public void onResponseReceived(final com.google.gwt.http.client.Request r,
                    final com.google.gwt.http.client.Response response) {
                if (response.getStatusCode() == com.google.gwt.http.client.Response.SC_OK
                        // Is this response still relevant to what the requester wants?
                        && requester.getText().startsWith(last_query)) {
                    final JSONValue json = JSONParser.parse(response.getText());
                    // In case this request returned nothing, we pretend the last
                    // suggestion ended with the largest character possible, so we
                    // won't send more requests to the server if the user keeps
                    // adding extra characters.
                    last_suggestion = last_query + "\377";
                    if (json != null && json.isArray() != null) {
                        final JSONArray results = json.isArray();
                        final int n = Math.min(request.getLimit(), results.size());
                        for (int i = 0; i < n; i++) {
                            final JSONValue suggestion = results.get(i);
                            if (suggestion == null || suggestion.isString() == null) {
                                continue;
                            }
                            final String suggestionstr = suggestion.isString().stringValue();
                            last_suggestion = suggestionstr;
                            cache.add(suggestionstr);
                        }
                        cache.requestSuggestions(request, callback);
                        pending_req = null;
                        pending_cb = null;
                    }
                }
                current = null; // Regardless of what happened above, this is done.
                if (pending_req != null) {
                    final Request req = pending_req;
                    final Callback cb = pending_cb;
                    pending_req = null;
                    pending_cb = null;
                    requestSuggestions(req, cb);
                }
            }
        });
    } catch (RequestException ignore) {
    }
}

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

License:Open Source License

private static String stringFromJsonValue(final JSONValue json) {
    if (json == null)
        return null;
    final JSONString jsonStr = json.isString();
    if (jsonStr == null)
        return null;
    return jsonStr.stringValue();
}

From source file:nl.mpi.tg.eg.experiment.client.presenter.AbstractStimulusPresenter.java

License:Open Source License

protected void stimulusFreeText(final Stimulus currentStimulus, String validationRegex, String keyCodeChallenge,
        String validationChallenge, final String allowedCharCodes, final int hotKey, String styleName,
        final int dataChannel) {
    final JSONObject storedStimulusJSONObject = localStorage
            .getStoredJSONObject(userResults.getUserData().getUserId(), currentStimulus);
    final String postName = "freeText";
    final JSONValue freeTextValue = (storedStimulusJSONObject == null) ? null
            : storedStimulusJSONObject.get(postName);
    StimulusFreeText stimulusFreeText = timedStimulusView.addStimulusFreeText(currentStimulus, postName,
            validationRegex, keyCodeChallenge, validationChallenge, allowedCharCodes,
            new SingleShotEventListner() {
                @Override//from  w w w .  j av  a  2 s.  c  om
                protected void singleShotFired() {
                    for (PresenterEventListner nextButtonEventListner : nextButtonEventListnerList) {
                        // this process is to make sure that group events are submitted and not just call nextStimulus
                        if (nextButtonEventListner.getHotKey() == hotKey) {
                            nextButtonEventListner.eventFired(null, this);
                        } else {
                            //                    nextStimulus("stimulusFreeTextEnter", false);
                        }
                    }
                    this.resetSingleShot();
                }
            }, hotKey, styleName, dataChannel,
            ((freeTextValue != null) ? freeTextValue.isString().stringValue() : null));
    stimulusFreeTextList.add(stimulusFreeText);
}

From source file:nl.mpi.tg.eg.experiment.client.presenter.AbstractStimulusPresenter.java

License:Open Source License

protected void sendGroupStoredMessage(final StimuliProvider stimulusProvider, final Stimulus currentStimulus,
        final String eventTag, final int originPhase, final int incrementPhase, String expectedRespondents) {
    final JSONObject storedStimulusJSONObject = localStorage
            .getStoredJSONObject(userResults.getUserData().getUserId(), currentStimulus);
    final JSONValue freeTextValue = (storedStimulusJSONObject == null) ? null
            : storedStimulusJSONObject.get("groupMessage");
    String messageString = ((freeTextValue != null) ? freeTextValue.isString().stringValue() : null);
    groupParticipantService.messageGroup(originPhase, incrementPhase, currentStimulus.getUniqueId(),
            Integer.toString(stimulusProvider.getCurrentStimulusIndex()), messageString,
            groupParticipantService.getResponseStimulusOptions(),
            groupParticipantService.getResponseStimulusId(), (int) userResults.getUserData().getCurrentScore(),
            expectedRespondents);// w w  w.  j  a va  2  s.  c  om
}

From source file:nl.mpi.tg.eg.experiment.client.view.TimedStimulusView.java

License:Open Source License

public StimulusFreeText addStimulusValidation(final LocalStorage localStorage, final UserId userId,
        final Stimulus currentStimulus, final String postName, final String validationRegex,
        final String validationChallenge, final int dataChannel) {
    final Label errorLabel = new Label(validationChallenge);
    errorLabel.setStylePrimaryName("metadataErrorMessage");
    errorLabel.setVisible(false);/*ww w.  j ava2  s.  co  m*/
    getActivePanel().add(errorLabel);
    return new StimulusFreeText() {
        @Override
        public Stimulus getStimulus() {
            return currentStimulus;
        }

        @Override
        public String getPostName() {
            return postName;
        }

        @Override
        public String getResponseTimes() {
            return null;
        }

        @Override
        public String getValue() {
            JSONObject storedStimulusJSONObject = localStorage.getStoredJSONObject(userId, currentStimulus);
            final JSONValue codeResponse = (storedStimulusJSONObject == null) ? null
                    : storedStimulusJSONObject.get(postName);
            return (codeResponse != null) ? codeResponse.isString().stringValue() : null;
        }

        @Override
        public boolean isValid() {
            final String currentValue = getValue();
            final boolean isValid;
            if (currentValue != null) {
                isValid = currentValue.matches(validationRegex);
            } else {
                isValid = false;
            }
            if (isValid) {
                errorLabel.setVisible(false);
                return true;
            } else {
                errorLabel.setText(validationChallenge);
                errorLabel.setVisible(true);
                return false;
            }
        }

        @Override
        public int getDataChannel() {
            return dataChannel;
        }

        @Override
        public void setFocus(boolean wantsFocus) {
            // todo: we could use a scroll to method to focus the message here
        }
    };
}

From source file:nl.sense_os.commonsense.main.client.viz.panels.table.SensorDataGrid.java

License:Open Source License

private String renderJsonValue(JSONObject json) {
    LOG.finest("Render JSON value: " + json.toString());

    StringBuilder sb = new StringBuilder();
    for (String key : json.keySet()) {
        // first print the field label
        sb.append("<b>").append(key).append(":</b> ");

        // get the field value
        JSONValue value = json.get(key);
        JSONString jsonString = value.isString();
        String valueString = "";
        if (null != jsonString) {
            valueString = jsonString.stringValue();
        } else {/*  w w  w . j  av a2s  .  c o m*/
            valueString = value.toString();
        }

        sb.append(valueString).append("<br />");
    }
    return sb.toString();
}

From source file:org.apache.solr.explorer.client.util.json.JSONUtils.java

License:Apache License

/**
 * Converts JSON value to string./*from  ww w. ja v a2s  .co  m*/
 *
 * @param jsonValue the JSON value.
 * @return the string value.
 */
public static String jsonValueToString(JSONValue jsonValue) {
    JSONString string = jsonValue.isString();
    if (string == null) {
        return null;
    } else {
        return string.stringValue();
    }
}

From source file:org.apache.solr.explorer.client.util.json.JSONUtils.java

License:Apache License

public static Boolean jsonValueToBoolean(JSONValue jsonValue) {
    JSONBoolean bool = jsonValue.isBoolean();
    if (bool != null) {
        return bool.booleanValue();
    }/*from  ww  w . j a va  2 s .  c o m*/
    JSONString string = jsonValue.isString();
    if (string != null) {
        return "true".equals(string.stringValue()) || "t".equals(string.stringValue())
                || "yes".equals(string.stringValue()) || "y".equals(string.stringValue());
    }
    throw new JSONException("Not a boolean: " + jsonValue);
}