List of usage examples for com.google.gwt.json.client JSONValue isArray
public JSONArray isArray()
From source file:rocket.json.client.JsonSerializer.java
License:Apache License
public List<Object> readList(final JSONValue jsonValue) { final List<Object> list = new ArrayList<Object>(); this.readCollection(jsonValue.isArray(), list); return list;//from w w w .j a va2 s. co m }
From source file:rocket.json.client.JsonSerializer.java
License:Apache License
public Set<Object> readSet(final JSONValue jsonValue) { final Set<Object> set = new HashSet<Object>(); this.readCollection(jsonValue.isArray(), set); return set;//from w w w .j a v a 2s . c o m }
From source file:rpc.client.data.JSONSerializer.java
License:Open Source License
private Object fromJSONValue(JSONValue jsonValue, Type expected) throws NoSuitableSerializableFactory { if (jsonValue == null) { return null; }// ww w . j a v a 2s .c o m // Null JSONNull asNull = jsonValue.isNull(); if (asNull != null) { return null; } // Boolean JSONBoolean asBoolean = jsonValue.isBoolean(); if (asBoolean != null) { return asBoolean.booleanValue(); } // Integer // Long // Float // Double JSONNumber asNumber = jsonValue.isNumber(); if (asNumber != null) { double value = asNumber.doubleValue(); if (expected.isInteger()) { return (int) value; } if (expected.isLong()) { return (long) value; } if (expected.isFloat()) { return (float) value; } if (expected.isDouble()) { return value; } } // String // Enum JSONString asString = jsonValue.isString(); if (asString != null) { if (expected.isEnum()) { String value = asString.stringValue(); return Enum.valueOf((Class) expected.getTypeClass(), value); } else { return asString.stringValue(); } } // Map // Serializable JSONObject asObject = jsonValue.isObject(); if (asObject != null) { if (expected.isMap()) { Map<Object, Object> map = new HashMap<Object, Object>(); Type keyType = expected.getParameterized(0); Type valueType = expected.getParameterized(1); if (!(keyType.isString() || keyType.isEnum())) { return null; } for (String key : asObject.keySet()) { JSONValue value = asObject.get(key); if (keyType.isString()) { map.put(key, fromJSONValue(value, valueType)); } if (keyType.isEnum()) { map.put(Enum.valueOf((Class) keyType.getTypeClass(), key), fromJSONValue(value, valueType)); } } return map; } else { if (provider == null) { throw new NoSuitableSerializableFactory(); } Serializable object = provider.make(expected); for (Map.Entry<String, Type> entry : object.fields().entrySet()) { String field = entry.getKey(); Type fieldType = entry.getValue(); JSONValue value = asObject.get(field); object.set(field, fromJSONValue(value, fieldType)); } return object; } } // List JSONArray asArray = jsonValue.isArray(); if (asArray != null) { int size = asArray.size(); List<Object> list = new ArrayList<Object>(); Type itemType = expected.getParameterized(0); for (int i = 0; i < size; i++) { JSONValue value = asArray.get(i); list.add(fromJSONValue(value, itemType)); } return list; } return null; }
From source file:stroom.util.client.JSONUtil.java
License:Apache License
public static JSONArray getArray(final JSONValue v) { if (v != null) { return v.isArray(); }/* w w w .ja v a 2s.co m*/ return null; }
From source file:tsd.client.QueryUi.java
License:Open Source License
/** * This is the entry point method./*from ww w. ja v a 2 s. com*/ */ public void onModuleLoad() { asyncGetJson(AGGREGATORS_URL, new GotJsonCallback() { public void got(final JSONValue json) { // Do we need more manual type checking? Not sure what will happen // in the browser if something other than an array is returned. final JSONArray aggs = json.isArray(); for (int i = 0; i < aggs.size(); i++) { aggregators.add(aggs.get(i).isString().stringValue()); } ((MetricForm) metrics.getWidget(0)).setAggregators(aggregators); refreshFromQueryString(); refreshGraph(); } }); // All UI elements need to regenerate the graph when changed. { final ValueChangeHandler<Date> vch = new ValueChangeHandler<Date>() { public void onValueChange(final ValueChangeEvent<Date> event) { refreshGraph(); } }; TextBox tb = start_datebox.getTextBox(); tb.addBlurHandler(refreshgraph); tb.addKeyPressHandler(refreshgraph); start_datebox.addValueChangeHandler(vch); tb = end_datebox.getTextBox(); tb.addBlurHandler(refreshgraph); tb.addKeyPressHandler(refreshgraph); end_datebox.addValueChangeHandler(vch); } autoreoload_interval.addBlurHandler(refreshgraph); autoreoload_interval.addKeyPressHandler(refreshgraph); yrange.addBlurHandler(refreshgraph); yrange.addKeyPressHandler(refreshgraph); y2range.addBlurHandler(refreshgraph); y2range.addKeyPressHandler(refreshgraph); ylog.addClickHandler(new AdjustYRangeCheckOnClick(ylog, yrange)); y2log.addClickHandler(new AdjustYRangeCheckOnClick(y2log, y2range)); ylog.addClickHandler(refreshgraph); y2log.addClickHandler(refreshgraph); ylabel.addBlurHandler(refreshgraph); ylabel.addKeyPressHandler(refreshgraph); y2label.addBlurHandler(refreshgraph); y2label.addKeyPressHandler(refreshgraph); yformat.addBlurHandler(refreshgraph); yformat.addKeyPressHandler(refreshgraph); y2format.addBlurHandler(refreshgraph); y2format.addKeyPressHandler(refreshgraph); wxh.addBlurHandler(refreshgraph); wxh.addKeyPressHandler(refreshgraph); horizontalkey.addClickHandler(refreshgraph); keybox.addClickHandler(refreshgraph); nokey.addClickHandler(refreshgraph); smooth.addClickHandler(refreshgraph); yrange.setValidationRegexp("^(" // Nothing or + "|\\[([-+.0-9eE]+|\\*)?" // "[start + ":([-+.0-9eE]+|\\*)?\\])$"); // :end]" yrange.setVisibleLength(5); yrange.setMaxLength(44); // MAX=2^26=20 chars: "[-$MAX:$MAX]" yrange.setText("[0:]"); y2range.setValidationRegexp("^(" // Nothing or + "|\\[([-+.0-9eE]+|\\*)?" // "[start + ":([-+.0-9eE]+|\\*)?\\])$"); // :end]" y2range.setVisibleLength(5); y2range.setMaxLength(44); // MAX=2^26=20 chars: "[-$MAX:$MAX]" y2range.setText("[0:]"); y2range.setEnabled(false); y2log.setEnabled(false); ylabel.setVisibleLength(10); ylabel.setMaxLength(50); // Arbitrary limit. y2label.setVisibleLength(10); y2label.setMaxLength(50); // Arbitrary limit. y2label.setEnabled(false); yformat.setValidationRegexp("^(|.*%..*)$"); // Nothing or at least one %? yformat.setVisibleLength(10); yformat.setMaxLength(16); // Arbitrary limit. y2format.setValidationRegexp("^(|.*%..*)$"); // Nothing or at least one %? y2format.setVisibleLength(10); y2format.setMaxLength(16); // Arbitrary limit. y2format.setEnabled(false); wxh.setValidationRegexp("^[1-9][0-9]{2,}x[1-9][0-9]{2,}$"); // 100x100 wxh.setVisibleLength(9); wxh.setMaxLength(11); // 99999x99999 wxh.setText((Window.getClientWidth() - 20) + "x" + (Window.getClientHeight() * 4 / 5)); final FlexTable table = new FlexTable(); table.setText(0, 0, "From"); { final HorizontalPanel hbox = new HorizontalPanel(); hbox.add(new InlineLabel("To")); final Anchor now = new Anchor("(now)"); now.addClickHandler(new ClickHandler() { public void onClick(final ClickEvent event) { end_datebox.setValue(new Date()); refreshGraph(); } }); hbox.add(now); hbox.add(autoreload); hbox.setWidth("100%"); table.setWidget(0, 1, hbox); } autoreload.addValueChangeHandler(new ValueChangeHandler<Boolean>() { @Override public void onValueChange(final ValueChangeEvent<Boolean> event) { if (autoreload.getValue()) { final HorizontalPanel hbox = new HorizontalPanel(); hbox.setWidth("100%"); hbox.add(new InlineLabel("Every:")); hbox.add(autoreoload_interval); hbox.add(new InlineLabel("seconds")); table.setWidget(1, 1, hbox); if (autoreoload_interval.getValue().isEmpty()) { autoreoload_interval.setValue("15"); } autoreoload_interval.setFocus(true); lastgraphuri = ""; // Force refreshGraph. refreshGraph(); // Trigger the 1st auto-reload } else { table.setWidget(1, 1, end_datebox); } } }); autoreoload_interval.setValidationRegexp("^([5-9]|[1-9][0-9]+)$"); // >=5s autoreoload_interval.setMaxLength(4); autoreoload_interval.setVisibleLength(8); table.setWidget(1, 0, start_datebox); table.setWidget(1, 1, end_datebox); { final HorizontalPanel hbox = new HorizontalPanel(); hbox.add(new InlineLabel("WxH:")); hbox.add(wxh); table.setWidget(0, 3, hbox); } { addMetricForm("metric 1", 0); metrics.selectTab(0); metrics.add(new InlineLabel("Loading..."), "+"); metrics.addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() { public void onBeforeSelection(final BeforeSelectionEvent<Integer> event) { final int item = event.getItem(); final int nitems = metrics.getWidgetCount(); if (item == nitems - 1) { // Last item: the "+" was clicked. event.cancel(); final MetricForm metric = addMetricForm("metric " + nitems, item); metrics.selectTab(item); metric.setFocus(true); } } }); table.setWidget(2, 0, metrics); } table.getFlexCellFormatter().setColSpan(2, 0, 2); table.getFlexCellFormatter().setRowSpan(1, 3, 2); final DecoratedTabPanel optpanel = new DecoratedTabPanel(); optpanel.add(makeAxesPanel(), "Axes"); optpanel.add(makeKeyPanel(), "Key"); optpanel.add(makeStylePanel(), "Style"); optpanel.selectTab(0); table.setWidget(1, 3, optpanel); final DecoratorPanel decorator = new DecoratorPanel(); decorator.setWidget(table); final VerticalPanel graphpanel = new VerticalPanel(); graphpanel.add(decorator); { final VerticalPanel graphvbox = new VerticalPanel(); graphvbox.add(graphstatus); graph.setVisible(false); // Put the graph image element and the zoombox elements inside the absolute panel graphbox.add(graph, 0, 0); zoom_box.setVisible(false); graphbox.add(zoom_box, 0, 0); graph.addMouseOverHandler(new MouseOverHandler() { public void onMouseOver(final MouseOverEvent event) { final Style style = graphbox.getElement().getStyle(); style.setCursor(Cursor.CROSSHAIR); } }); graph.addMouseOutHandler(new MouseOutHandler() { public void onMouseOut(final MouseOutEvent event) { final Style style = graphbox.getElement().getStyle(); style.setCursor(Cursor.AUTO); } }); graphvbox.add(graphbox); graph.addErrorHandler(new ErrorHandler() { public void onError(final ErrorEvent event) { graphstatus.setText("Oops, failed to load the graph."); } }); graph.addLoadHandler(new LoadHandler() { public void onLoad(final LoadEvent event) { graphbox.setWidth(graph.getWidth() + "px"); graphbox.setHeight(graph.getHeight() + "px"); } }); graphpanel.add(graphvbox); } final DecoratedTabPanel mainpanel = new DecoratedTabPanel(); mainpanel.setWidth("100%"); mainpanel.add(graphpanel, "Graph"); mainpanel.add(stats_table, "Stats"); mainpanel.add(logs, "Logs"); mainpanel.add(build_data, "Version"); mainpanel.selectTab(0); mainpanel.addBeforeSelectionHandler(new BeforeSelectionHandler<Integer>() { public void onBeforeSelection(final BeforeSelectionEvent<Integer> event) { clearError(); final int item = event.getItem(); switch (item) { case 1: refreshStats(); return; case 2: refreshLogs(); return; case 3: refreshVersion(); return; } } }); final VerticalPanel root = new VerticalPanel(); root.setWidth("100%"); root.add(current_error); current_error.setVisible(false); current_error.addStyleName("dateBoxFormatError"); root.add(mainpanel); RootPanel.get("queryuimain").add(root); // Must be done at the end, once all the widgets are attached. ensureSameWidgetSize(optpanel); History.addHistoryListener(this); }
From source file:tsd.client.RemoteOracle.java
License:Open Source License
@Override public void requestSuggestions(final Request request, final Callback callback) { if (current != null) { pending_req = request;/*from w w w .j ava2 s . c om*/ 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) { 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); } // Is this response still relevant to what the requester wants? if (requester.getText().startsWith(last_query)) { 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:virtuozo.infra.HttpMethod.java
License:Apache License
public <J extends JavaScriptObject> void send(JSOCallback<J> callback) { this.defaultAcceptType(MediaType.JSON); this.send(new CallbackProxy<J>(this, callback) { @SuppressWarnings("unchecked") protected J parse(String content) { try { JSONValue val = JSONParser.parseStrict(content); if (val.isObject() != null) { return (J) val.isObject().getJavaScriptObject(); }/*from w w w . ja v a2s . c o m*/ if (val.isArray() != null) { return (J) val.isArray().getJavaScriptObject(); } throw new AsyncException("Response was not a JSON object"); } catch (Exception e) { throw new AsyncException("Response was not a valid JSON document", e); } } }); }