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

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

Introduction

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

Prototype

public JSONNumber isNumber() 

Source Link

Document

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

Usage

From source file:org.nuxeo.ecm.platform.gwt.client.model.Document.java

License:Open Source License

public String getDateProperty(String schema, String property) {
    JSONValue v = getProperty(schema, property);
    if (v != null && v.isObject() != null) {
        JSONObject o = v.isObject();/* w  w  w . j a v a  2  s.com*/
        JSONValue time = o.get("timeInMillis");
        if (time != null && time.isNumber() != null) {
            Date date = new Date((long) time.isNumber().doubleValue());
            return date.toString();
        }
    }
    return null;
}

From source file:org.nuxeo.ecm.platform.gwt.client.model.Document.java

License:Open Source License

public double getNumberProperty(String schema, String property, double defaultValue) {
    JSONValue v = getProperty(schema, property);
    if (v != null && v.isString() != null) {
        return v.isNumber().doubleValue();
    }//from   w w  w.  j  av  a 2  s .c om
    return defaultValue;
}

From source file:org.onebusaway.webapp.gwt.common.rpc.JsonLibrary.java

License:Apache License

public static Double getJsonDouble(JSONObject object, String key) {
    JSONValue value = object.get(key);
    if (value == null)
        return null;
    JSONNumber v = value.isNumber();
    if (v == null)
        return null;
    return new Double(v.doubleValue());
}

From source file:org.openremote.modeler.client.gxtextends.NestedJsonLoadResultReader.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  w  ww.j ava2 s  . c  o  m
public D read(Object loadConfig, Object data) {
    JSONObject jsonRoot = null;
    if (data instanceof JavaScriptObject) {
        jsonRoot = new JSONObject((JavaScriptObject) data);
    } else {
        jsonRoot = (JSONObject) JSONParser.parse((String) data);
    }

    // You can specify root using dot separate. eg, vendors.vendor 
    String[] roots = myModelType.getRoot().split("\\.");
    JSONValue rootValue = null;
    JSONArray root = null;
    for (int i = 0; i < roots.length; i++) {
        rootValue = jsonRoot.get(roots[i]);
        if (i == roots.length - 1) {
            if (rootValue instanceof JSONObject) {
                root = new JSONArray();
                root.set(0, rootValue);
            } else {
                root = (JSONArray) rootValue;
            }
        } else {
            jsonRoot = (JSONObject) jsonRoot.get(roots[i]);
        }
    }

    int size = root.size();
    ArrayList<ModelData> models = new ArrayList<ModelData>();
    for (int i = 0; i < size; i++) {
        JSONObject obj = (JSONObject) root.get(i);
        ModelData model = newModelInstance();
        for (int j = 0; j < myModelType.getFieldCount(); j++) {
            DataField field = myModelType.getField(j);
            String name = field.getName();
            Class type = field.getType();
            String map = field.getMap() != null ? field.getMap() : field.getName();
            JSONValue value = obj.get(map);

            if (value == null) {
                continue;
            }
            if (value.isArray() != null) {
                // nothing
            } else if (value.isBoolean() != null) {
                model.set(name, value.isBoolean().booleanValue());
            } else if (value.isNumber() != null) {
                if (type != null) {
                    Double d = value.isNumber().doubleValue();
                    if (type.equals(Integer.class)) {
                        model.set(name, d.intValue());
                    } else if (type.equals(Long.class)) {
                        model.set(name, d.longValue());
                    } else if (type.equals(Float.class)) {
                        model.set(name, d.floatValue());
                    } else {
                        model.set(name, d);
                    }
                } else {
                    // convert no type number to string.
                    model.set(name, value.isNumber().toString());
                }
            } else if (value.isObject() != null) {
                // nothing
            } else if (value.isString() != null) {
                String s = value.isString().stringValue();
                if (type != null) {
                    if (type.equals(Date.class)) {
                        if (field.getFormat().equals("timestamp")) {
                            Date d = new Date(Long.parseLong(s) * 1000);
                            model.set(name, d);
                        } else {
                            DateTimeFormat format = DateTimeFormat.getFormat(field.getFormat());
                            Date d = format.parse(s);
                            model.set(name, d);
                        }
                    }
                } else {
                    model.set(name, s);
                }
            } else if (value.isNull() != null) {
                model.set(name, null);
            }
        }
        models.add(model);
    }
    int totalCount = models.size();
    if (myModelType.getTotalName() != null) {
        totalCount = getTotalCount(jsonRoot);
    }
    return (D) createReturnData(loadConfig, models, totalCount);
}

From source file:org.ow2.proactive_grid_cloud_portal.common.client.json.JSONUtils.java

License:Open Source License

private static int retrieveErrorCode(JSONObject exc) {
    JSONValue val = exc.get("httpErrorCode");
    if (val == null || val.isNumber() == null) {
        return -1;
    } else {//w w w.  j a  v a 2s .c  o  m
        return (int) val.isNumber().doubleValue();
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.client.monitoring.charts.CpusUsageLineChart.java

License:Open Source License

@Override
public void processResult(String result) {
    JSONObject object = controller.parseJSON(result).isObject();
    if (object != null) {

        String timeStamp = DateTimeFormat.getFormat(PredefinedFormat.HOUR24_MINUTE)
                .format(new Date(System.currentTimeMillis()));

        addRow();//  w  ww.j  ava2  s  .  c o  m
        loadTable.setValue(loadTable.getNumberOfRows() - 1, 0, timeStamp);

        boolean initColumns = super.initColumns();
        int colIndex = 1;
        for (String key : object.keySet()) {

            if (initColumns) {
                loadTable.addColumn(ColumnType.NUMBER, beautifyName(key));
            }

            double value = 0;
            JSONValue jsonVal = object.get(key).isArray().get(0).isObject().get("value");
            if (jsonVal != null && jsonVal.isNumber() != null) {
                value = jsonVal.isNumber().doubleValue();
            }
            loadTable.setValue(loadTable.getNumberOfRows() - 1, colIndex++, value);
        }

        loadChart.draw(loadTable, loadOpts);
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.client.monitoring.charts.MBeanDetailedView.java

License:Open Source License

public void load(final RMController controller, String jmxServerUrl, String mbean, List<String> attrs) {
    DetailViewerField[] fields = new DetailViewerField[attrs.size()];

    for (int i = 0; i < fields.length; i++) {
        fields[i] = new DetailViewerField(attrs.get(i));
    }/*from   w  w w.jav a  2 s  .c  o m*/

    setFields(fields);

    final RMServiceAsync rm = controller.getRMService();
    final RMModel model = controller.getModel();
    final long t = System.currentTimeMillis();

    final LoginModel loginModel = LoginModel.getInstance();

    // loading runtime info
    rm.getNodeMBeanInfo(loginModel.getSessionId(), jmxServerUrl, mbean, attrs, new AsyncCallback<String>() {
        public void onSuccess(String result) {

            if (extraCallback != null) {
                extraCallback.onSuccess(result);
            }

            if (!loginModel.isLoggedIn())
                return;

            LogModel.getInstance()
                    .logMessage("Fetched JVM Runtime info in " + (System.currentTimeMillis() - t) + "ms");
            JSONArray array = controller.parseJSON(result).isArray();
            if (array != null) {
                DetailViewerRecord dv = new DetailViewerRecord();
                for (int i = 0; i < array.size(); i++) {
                    try {
                        JSONObject property = array.get(i).isObject();
                        String name = property.get("name").isString().stringValue();
                        JSONValue value = property.get("value");
                        String valueStr = "";

                        if (value.isString() != null) {
                            valueStr = value.isString().stringValue();
                        } else if (value.isNumber() != null) {
                            valueStr = value.isNumber().toString();
                        }

                        dv.setAttribute(name, valueStr);
                    } catch (Exception e) {
                        // ignore it
                    }
                }
                setData(new DetailViewerRecord[] { dv });
            }

        }

        public void onFailure(Throwable caught) {
            if (extraCallback != null) {
                extraCallback.onFailure(caught);
            }

            if (JSONUtils.getJsonErrorCode(caught) == 401) {
                LogModel.getInstance().logMessage("You have been disconnected from the server.");
            }
        }
    });
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.client.monitoring.charts.MBeanSourceDetailedView.java

License:Open Source License

public void reload() {
    DetailViewerField[] fields = new DetailViewerField[attrs.size()];

    for (int i = 0; i < fields.length; i++) {
        fields[i] = new DetailViewerField(attrs.get(i));
    }//from w ww. java  2  s .c  om

    setFields(fields);

    final RMServiceAsync rm = controller.getRMService();
    final RMModel model = controller.getModel();
    final long t = System.currentTimeMillis();

    final LoginModel loginModel = LoginModel.getInstance();

    // loading runtime info
    rm.getNodeMBeanInfo(loginModel.getSessionId(), jmxServerUrl, mbean, attrs, new AsyncCallback<String>() {
        public void onSuccess(String result) {

            if (extraCallback != null) {
                extraCallback.onSuccess(result);
            }

            if (!loginModel.isLoggedIn())
                return;

            LogModel.getInstance()
                    .logMessage("Fetched JVM Runtime info in " + (System.currentTimeMillis() - t) + "ms");
            JSONArray array = controller.parseJSON(result).isArray();
            if (array != null) {
                DetailViewerRecord dv = new DetailViewerRecord();
                for (int i = 0; i < array.size(); i++) {
                    try {
                        JSONObject property = array.get(i).isObject();
                        String name = property.get("name").isString().stringValue();
                        JSONValue value = property.get("value");
                        String valueStr = "";

                        if (value.isString() != null) {
                            valueStr = value.isString().stringValue();
                        } else if (value.isNumber() != null) {
                            valueStr = value.isNumber().toString();
                        } else if (value.isArray() != null) {
                            JSONArray values = value.isArray();
                            for (int j = 0; j < values.size(); j++)
                                valueStr += values.get(j).isString().stringValue() + " ";
                        } else if (value.isObject() != null) {
                            valueStr = value.toString();
                        } else {
                            valueStr = value.toString();
                        }

                        dv.setAttribute(name, valueStr);
                    } catch (Exception e) {
                        // ignore it
                    }
                }
                setData(new DetailViewerRecord[] { dv });
            }

        }

        public void onFailure(Throwable caught) {
            if (extraCallback != null) {
                String errmessage = caught.getMessage();
                if (caught instanceof RestServerException
                        && errmessage.contains(MonitoringSourceView.NO_MONITORING_INFO_EXCEPTION_STRING)) {
                    extraCallback
                            .onFailure(new Exception("Node Source monitoring information " + "not available."));
                } else if (caught instanceof RestServerException
                        && errmessage.contains(MonitoringSourceView.ACCESS_DENIED_EXCEPTION_STRING)) {
                    extraCallback.onFailure(new Exception(
                            "The current user is not authorized to get Node Source monitoring information. "));
                } else {
                    extraCallback.onFailure(caught);
                }
            }

            if (JSONUtils.getJsonErrorCode(caught) == 401) {
                LogModel.getInstance().logMessage("You have been disconnected from the server.");
            }
        }
    });
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.client.RMController.java

License:Open Source License

/**
 * Perform the server call to fetch RRD history statistics
 *//*ww w  . jav a  2s. co  m*/
private void fetchStatHistory() {
    String range = "";
    String[] sources = new String[] { "BusyNodesCount", "FreeNodesCount", "DownNodesCount",
            "AvailableNodesCount", "AverageActivity" };
    long updateFreq = Range.YEAR_1.getUpdateFrequency();
    boolean changedRange = false;
    for (String src : sources) {
        if (model.getStatHistory(src) != null
                && !model.getStatHistory(src).range.equals(model.getRequestedStatHistoryRange(src))) {
            changedRange = true;
        }

        Range r = model.getRequestedStatHistoryRange(src);
        range += r.getChar();
        if (r.getUpdateFrequency() < updateFreq)
            updateFreq = r.getUpdateFrequency();
    }

    final long now = System.currentTimeMillis();
    final long dt = now - this.lastStatHistReq;

    // do not update stats every 5sec if the graphed range is large
    if (dt > updateFreq * 1000 || changedRange) {
        this.lastStatHistReq = now;

        this.statHistReq = rm.getStatHistory(LoginModel.getInstance().getSessionId(), range,
                new AsyncCallback<String>() {
                    @Override
                    public void onSuccess(String result) {

                        JSONValue val = RMController.this.parseJSON(result);
                        JSONObject obj = val.isObject();

                        HashMap<String, StatHistory> stats = new HashMap<String, StatHistory>();
                        for (String source : obj.keySet()) {
                            JSONArray arr = obj.get(source).isArray();

                            ArrayList<Double> values = new ArrayList<Double>();
                            for (int i = 0; i < arr.size(); i++) {
                                JSONValue dval = arr.get(i);
                                if (dval.isNumber() != null) {
                                    values.add(dval.isNumber().doubleValue());
                                } else if (i < arr.size() - 1) {
                                    values.add(Double.NaN);
                                }

                            }
                            StatHistory st = new StatHistory(source, values,
                                    model.getRequestedStatHistoryRange(source));
                            stats.put(source, st);
                        }
                        model.setStatHistory(stats);
                        LogModel.getInstance().logMessage(
                                "Updated Statistics History in " + (System.currentTimeMillis() - now) + "ms");
                    }

                    @Override
                    public void onFailure(Throwable caught) {
                        if (JSONUtils.getJsonErrorCode(caught) == 401) {
                            teardown("You have been disconnected from the server.");
                        } else {
                            error("Failed to fetch Statistics History: "
                                    + JSONUtils.getJsonErrorMessage(caught));
                        }
                    }
                });
    }

    /*
     * max nodes from RRD on RM 
     * not used right now, uncomment if needed
     * 
    List<String> attrs = new ArrayList<String>();
    attrs.add("MaxFreeNodes");
    attrs.add("MaxBusyNodes");
    attrs.add("MaxDownNodes");
    // attrs.add("MaxTotalNodes"); // for some reason there is no Max Total Nodes...
            
    rm.getMBeanInfo(model.getSessionId(),
      "ProActiveResourceManager:name=RuntimeData", attrs,
      new AsyncCallback<String>() {
            
         @Override
         public void onFailure(Throwable caught) {
            error("Failed to get MBean Info: "
                  + getJsonErrorMessage(caught));
            
         }
            
         @Override
         public void onSuccess(String result) {
            JSONArray arr = JSONParser.parseStrict(result)
                  .isArray();
            for (int i = 0; i < arr.size(); i++) {
               String name = arr.get(i).isObject().get("name")
                     .isString().stringValue();
               int value = (int) arr.get(i).isObject()
                     .get("value").isNumber().doubleValue();
               if (name.equals("MaxFreeNodes")) {
                  model.setMaxNumFree(value);
               } else if (name.equals("MaxBusyNodes")) {
                  model.setMaxNumBusy(value);
               } else if (name.equals("MaxDownNodes")) {
                  model.setMaxNumDown(value);
               }
            }
            
         }
      });
     */
}

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.json.SchedulerJSONUtils.java

License:Open Source License

protected static long getSize(JSONObject obj) throws JSONException {
    JSONValue jsonTotalValue = obj.get("size");
    if (jsonTotalValue == null) {
        throw new JSONException("Expected JSON Object with attribute total: " + obj.toString());
    }/*from   w w w.  j a  va2 s  . c o m*/
    JSONNumber jsonTotal = jsonTotalValue.isNumber();
    if (jsonTotal == null) {
        throw new JSONException("Expected JSON number: " + jsonTotalValue.toString());
    }
    return (long) jsonTotal.doubleValue();
}