use of com.google.gwt.json.client.JSONValue in project che by eclipse.
the class EditorPropertiesManager method readPropertiesFromJson.
private static Map<String, JSONValue> readPropertiesFromJson(String jsonProperties) {
Map<String, JSONValue> result = new HashMap<>();
JSONValue parsed = JSONParser.parseStrict(jsonProperties);
JSONObject jsonObj = parsed.isObject();
if (jsonObj != null) {
for (String key : jsonObj.keySet()) {
JSONValue jsonValue = jsonObj.get(key);
result.put(key, jsonValue);
}
}
return result;
}
use of com.google.gwt.json.client.JSONValue in project gwt-test-utils by gwt-test-utils.
the class JSONArrayPatcher method getInnerList.
private static List<JSONValue> getInnerList(JSONArray jsonArray) {
JavaScriptObject jsArray = jsonArray.getJavaScriptObject();
List<JSONValue> list = JavaScriptObjects.getObject(jsArray, JSONARRAY_LIST);
if (list == null) {
list = new ArrayList<JSONValue>();
JavaScriptObjects.setProperty(jsArray, JSONARRAY_LIST, list);
}
return list;
}
use of com.google.gwt.json.client.JSONValue in project opentsdb by OpenTSDB.
the class QueryUi method onModuleLoad.
/**
* This is the entry point method.
*/
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);
global_annotations.addBlurHandler(refreshgraph);
global_annotations.addKeyPressHandler(refreshgraph);
horizontalkey.addClickHandler(refreshgraph);
keybox.addClickHandler(refreshgraph);
nokey.addClickHandler(refreshgraph);
smooth.addClickHandler(refreshgraph);
styles.addChangeHandler(refreshgraph);
yrange.setValidationRegexp(// Nothing or
"^(" + // "[start
"|\\[([-+.0-9eE]+|\\*)?" + // :end]"
":([-+.0-9eE]+|\\*)?\\])$");
yrange.setVisibleLength(5);
// MAX=2^26=20 chars: "[-$MAX:$MAX]"
yrange.setMaxLength(44);
yrange.setText("[0:]");
y2range.setValidationRegexp(// Nothing or
"^(" + // "[start
"|\\[([-+.0-9eE]+|\\*)?" + // :end]"
":([-+.0-9eE]+|\\*)?\\])$");
y2range.setVisibleLength(5);
// MAX=2^26=20 chars: "[-$MAX:$MAX]"
y2range.setMaxLength(44);
y2range.setText("[0:]");
y2range.setEnabled(false);
y2log.setEnabled(false);
ylabel.setVisibleLength(10);
// Arbitrary limit.
ylabel.setMaxLength(50);
y2label.setVisibleLength(10);
// Arbitrary limit.
y2label.setMaxLength(50);
y2label.setEnabled(false);
// Nothing or at least one %?
yformat.setValidationRegexp("^(|.*%..*)$");
yformat.setVisibleLength(10);
// Arbitrary limit.
yformat.setMaxLength(16);
// Nothing or at least one %?
y2format.setValidationRegexp("^(|.*%..*)$");
y2format.setVisibleLength(10);
// Arbitrary limit.
y2format.setMaxLength(16);
y2format.setEnabled(false);
// 100x100
wxh.setValidationRegexp("^[1-9][0-9]{2,}x[1-9][0-9]{2,}$");
wxh.setVisibleLength(9);
// 99999x99999
wxh.setMaxLength(11);
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);
// Force refreshGraph.
lastgraphuri = "";
// Trigger the 1st auto-reload
refreshGraph();
} else {
table.setWidget(1, 1, end_datebox);
}
}
});
// >=5s
autoreoload_interval.setValidationRegexp("^([5-9]|[1-9][0-9]+)$");
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);
}
{
final HorizontalPanel hbox = new HorizontalPanel();
hbox.add(global_annotations);
table.setWidget(0, 4, 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);
table.getFlexCellFormatter().setColSpan(1, 3, 2);
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);
}
use of com.google.gwt.json.client.JSONValue in project opentsdb by OpenTSDB.
the class QueryUi method refreshGraph.
private void refreshGraph() {
final Date start = start_datebox.getValue();
if (start == null) {
graphstatus.setText("Please specify a start time.");
return;
}
final Date end = end_datebox.getValue();
if (end != null && !autoreload.getValue()) {
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=");
final String start_text = start_datebox.getTextBox().getText();
if (start_text.endsWith(" ago") || start_text.endsWith("-ago")) {
url.append(start_text);
} else {
url.append(FULLDATE.format(start));
}
if (end != null && !autoreload.getValue()) {
url.append("&end=");
final String end_text = end_datebox.getTextBox().getText();
if (end_text.endsWith(" ago") || end_text.endsWith("-ago")) {
url.append(end_text);
} else {
url.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 (global_annotations.getValue()) {
url.append("&global_annotations");
}
if (timezone.length() > 1)
url.append("&tz=").append(timezone);
if (!addAllMetrics(url)) {
return;
}
addLabels(url);
addFormats(url);
addYRanges(url);
addLogscales(url);
if (nokey.getValue()) {
url.append("&nokey");
} else if (!keypos.isEmpty() || horizontalkey.getValue()) {
url.append("&key=");
if (!keypos.isEmpty()) {
url.append(keypos);
}
if (horizontalkey.getValue()) {
url.append(" horiz");
}
if (keybox.getValue()) {
url.append(" box");
}
}
url.append("&wxh=").append(wxh.getText());
if (smooth.getValue()) {
url.append("&smooth=csplines");
}
url.append("&style=").append(styles.getValue(styles.getSelectedIndex()));
if (hide_annotations) {
url.append("&no_annotations=true");
}
if (show_global_annotations) {
url.append("&global_annotations=true");
}
final String unencodedUri = url.toString();
final String uri = URL.encode(unencodedUri);
if (uri.equals(lastgraphuri)) {
// Don't re-request the same graph.
return;
} 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();
String history = // Remove "q?".
unencodedUri.substring(2).replaceFirst("ignore=[^&]*&", // Unnecessary cruft.
"");
if (autoreload.getValue()) {
history += "&autoreload=" + autoreoload_interval.getText();
}
if (!history.equals(URL.decode(History.getToken()))) {
History.newItem(history, false);
}
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();
// Skip if no tags were associated with the query.
if (null != tags) {
for (int j = 0; j < tags.size(); j++) {
metric.autoSuggestTag(tags.get(j).isString().stringValue());
}
}
}
}
if (autoreload.getValue()) {
final int reload_in = Integer.parseInt(autoreoload_interval.getValue());
if (reload_in >= 5) {
autoreoload_timer = new Timer() {
public void run() {
// hasn't been updated in the mean time.
if (autoreload.getValue() && 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();
}
}
});
}
use of com.google.gwt.json.client.JSONValue in project opentsdb by OpenTSDB.
the class RemoteOracle method requestSuggestions.
@Override
public void requestSuggestions(final Request request, final Callback callback) {
if (current != null) {
pending_req = request;
pending_cb = callback;
return;
}
current = callback;
{
final String this_query = request.getQuery();
// 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) {
// Something bad happened, drop the current request.
current = null;
if (pending_req != null) {
// But if we have another waiting...
// ... try it now.
requestSuggestions(pending_req, pending_cb);
}
}
// 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;
}
}
}
// Regardless of what happened above, this is done.
current = null;
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) {
}
}
Aggregations