Example usage for com.google.gson JsonElement getAsDouble

List of usage examples for com.google.gson JsonElement getAsDouble

Introduction

In this page you can find the example usage for com.google.gson JsonElement getAsDouble.

Prototype

public double getAsDouble() 

Source Link

Document

convenience method to get this element as a primitive double value.

Usage

From source file:com.getperka.flatpack.codexes.NumberCodex.java

License:Apache License

@Override
public N readNotNull(JsonElement element, DeserializationContext context) {
    Object toReturn;//from   ww  w.  ja va  2  s  .  c  o m
    if (BigDecimal.class.equals(clazz)) {
        toReturn = element.getAsBigDecimal();
    } else if (BigInteger.class.equals(clazz)) {
        toReturn = element.getAsBigInteger();
    } else if (Byte.class.equals(clazz)) {
        toReturn = element.getAsByte();
    } else if (Double.class.equals(clazz)) {
        toReturn = element.getAsDouble();
    } else if (Float.class.equals(clazz)) {
        toReturn = element.getAsFloat();
    } else if (Integer.class.equals(clazz)) {
        toReturn = element.getAsInt();
    } else if (Long.class.equals(clazz)) {
        toReturn = element.getAsLong();
    } else if (Short.class.equals(clazz)) {
        toReturn = element.getAsShort();
    } else {
        throw new UnsupportedOperationException("Unimplemented Number type " + clazz.getName());
    }
    return clazz.cast(toReturn);
}

From source file:com.github.ithildir.airbot.util.ApiAiUtil.java

License:Open Source License

public static double[] getResponseCoordinates(JsonObject responseJsonObject) {

    JsonObject originalRequestJsonObject = responseJsonObject.getAsJsonObject("originalRequest");

    JsonObject dataJsonObject = originalRequestJsonObject.getAsJsonObject("data");

    JsonObject deviceJsonObject = dataJsonObject.getAsJsonObject("device");

    if (deviceJsonObject == null) {
        return null;
    }//from   ww w .j  a v  a  2 s . com

    JsonObject locationJsonObject = deviceJsonObject.getAsJsonObject("location");

    if (locationJsonObject == null) {
        return null;
    }

    JsonObject coordinatesJsonObject = locationJsonObject.getAsJsonObject("coordinates");

    if (coordinatesJsonObject == null) {
        return null;
    }

    JsonElement latitudeJsonElement = coordinatesJsonObject.get("latitude");
    JsonElement longitudeJsonElement = coordinatesJsonObject.get("longitude");

    return new double[] { latitudeJsonElement.getAsDouble(), longitudeJsonElement.getAsDouble() };
}

From source file:com.graphaware.module.es.Neo4jElasticVerifier.java

License:Open Source License

private void checkDoubleArray(JsonObject source, String key, Map<String, Object> properties) {
    assertTrue(source.get(key) instanceof JsonArray);
    JsonArray jsonArray = source.get(key).getAsJsonArray();
    TreeSet<Double> esSet = new TreeSet();
    for (JsonElement element : jsonArray) {
        esSet.add(element.getAsDouble());
    }//from   ww  w. j  ava  2s  . co m
    TreeSet<Double> nodeSet = new TreeSet();
    double[] propertyArray = (double[]) properties.get(key);
    for (double element : propertyArray) {
        nodeSet.add(element);
    }
    assertEquals(esSet, nodeSet);
}

From source file:com.impetus.client.couchdb.CouchDBClient.java

License:Apache License

/**
 * Sets the aggregated values in result.
 * /*from   w ww  .j a  v  a2 s .c  o  m*/
 * @param results
 *            the results
 * @param interpreter
 *            the interpreter
 * @param array
 *            the array
 */
private void setAggregatedValuesInResult(List results, CouchDBQueryInterpreter interpreter, JsonArray array) {
    for (JsonElement json : array) {
        JsonElement value = json.getAsJsonObject().get("value");
        if (interpreter.getAggregationType().equals(CouchDBConstants.COUNT))
            results.add(value.getAsInt());
        else
            results.add(value.getAsDouble());
    }
}

From source file:com.nimbits.server.gson.deserializer.ValueDeserializer.java

License:Apache License

@Override
public Value deserialize(final JsonElement jsonElement, final Type type,
        final JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    Location location;/*from   w ww  .j  av  a 2s .  c om*/

    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonElement valueElement = jsonObject.get("d");
    JsonElement dataElement = jsonObject.get("dx");
    JsonElement latElement = jsonObject.get("lt");
    JsonElement lngElement = jsonObject.get("lg");
    JsonElement timestampElement = jsonObject.get("t");
    String data = dataElement == null ? null : dataElement.getAsString();
    Double lat = latElement == null || latElement.isJsonNull() ? null : latElement.getAsDouble();
    Double lng = lngElement == null || lngElement.isJsonNull() ? null : lngElement.getAsDouble();
    Double value = valueElement == null || valueElement.isJsonNull() ? null : valueElement.getAsDouble();
    Long timestamp = timestampElement == null || timestampElement.isJsonNull() ? 0
            : timestampElement.getAsLong();

    if (lat != null && lng != null) {
        location = LocationFactory.createLocation(lat, lng);
    } else {
        location = LocationFactory.createEmptyLocation();
    }

    Date time = timestamp > 0 ? new Date(timestamp) : new Date();
    ValueData valueData;
    if (data != null && data.length() > 0) {
        valueData = ValueDataModel.getInstance(SimpleValue.getInstance(data));
    } else {
        valueData = ValueDataModel.getEmptyInstance();
    }

    return ValueFactory.createValueModel(location, value, time, valueData, AlertType.OK);

}

From source file:com.redcanari.ui.WebKitBrowser.java

License:Open Source License

private void createDetailPane() {
    detailPane = new TabPane();

    javaScriptConsoleTab = new JavaScriptConsoleTab(webEngine);
    addErrorListener(javaScriptConsoleTab::handleError);
    addAlertListener(javaScriptConsoleTab::handleAlert);

    crossSiteScriptingTrackerTab = new CrossSiteScriptingTrackerTab(webEngine);
    addAlertListener(crossSiteScriptingTrackerTab::handleAlert);

    pageResourcesTab = new PageResourcesTab(webEngine);

    promptDialog = new JSInputDialog();

    Tab javaScriptEditorTab = new Tab("BurpScript IDE");
    javaScriptEditorTab.selectedProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue)
            masterDetailPane.setDividerPositions(0.5);
    });/*from  w ww  .j a  v a 2 s.c om*/
    JavaScriptEditor javaScriptEditor = new JavaScriptEditor(webEngine, controller, false);
    javaScriptEditor.setJavaScriptConsoleTab(javaScriptConsoleTab);
    javaScriptEditorTab.setContent(javaScriptEditor);

    Tab trafficBrowserTab = new Tab("Network");
    trafficBrowser = new TrafficBrowser();
    trafficBrowserTab.setContent(trafficBrowser);

    Debugger debugger = webEngine.impl_getDebugger();
    debugger.setEnabled(true);
    debugger.sendMessage("{\"id\": 1, \"method\":\"Network.enable\"}");
    debugger.setMessageCallback(new Callback<String, Void>() {

        ConcurrentHashMap<String, Traffic> trafficState = new ConcurrentHashMap<>();

        @Override
        public Void call(String param) {
            JsonParser parser = new JsonParser();
            JsonObject object = parser.parse(param).getAsJsonObject();

            String method = object.get("method").getAsString();
            JsonObject params = object.getAsJsonObject("params");
            JsonObject request = params.getAsJsonObject("request");
            JsonObject response = params.getAsJsonObject("response");
            String requestId = params.get("requestId").getAsString();

            Instant timeStamp;
            JsonElement epochObject = params.get("timestamp");
            if (epochObject != null) {
                double epoch = epochObject.getAsDouble();
                timeStamp = Instant.ofEpochSecond((long) Math.floor(epoch),
                        (long) (epoch * 1000000000 % 1000000000));
            } else {
                timeStamp = Instant.now();
            }

            Traffic traffic = null;

            switch (method) {
            case "Network.requestWillBeSent":
                URL url = null;
                String urlString = request.get("url").getAsString();

                try {
                    url = new URL(urlString);
                } catch (MalformedURLException e) {
                    //                            e.printStackTrace();
                }
                trafficState.put(requestId,
                        new Traffic((url == null) ? urlString : url.getFile(), timeStamp,
                                (url == null) ? "" : url.getHost(), request.get("method").getAsString(),
                                params.get("documentURL").getAsString()));
                break;
            case "Network.responseReceived":
                traffic = trafficState.get(requestId);
                JsonObject headers = response.getAsJsonObject("headers");
                JsonElement contentType = headers.get("Content-Type");
                JsonElement contentLength = headers.get("Content-Length");
                traffic.setType((contentType == null) ? "" : contentType.getAsString());
                JsonElement requestLine = headers.get("");
                if (requestLine != null) {
                    String[] requestLineParts = requestLine.getAsString().split(" ", 3);
                    traffic.setStatusCode(new Integer(requestLineParts[1]));
                    traffic.setStatusText(requestLineParts[2]);
                    traffic.setSize((contentLength == null) ? "0" : contentLength.getAsString());
                } else {
                    traffic.setStatusCode(200);
                    traffic.setStatusText("OK");
                    traffic.setSize("0");
                }
                break;
            case "Network.loadingFinished":
                traffic = trafficState.get(requestId);
                traffic.setEndTime(timeStamp);
                trafficBrowser.getTraffic().add(traffic);
                trafficState.remove(requestId);
                if (traffic.getEndTime().isAfter(trafficBrowser.getEndTime())) {
                    trafficBrowser.setEndTime(traffic.getEndTime());
                }
            }
            return null;
        }
    });

    detailPane.getTabs().addAll(javaScriptConsoleTab, crossSiteScriptingTrackerTab, pageResourcesTab,
            trafficBrowserTab, javaScriptEditorTab
    //                new ImagesTab(webEngine)
    );

    detailPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
}

From source file:com.shared.rides.service.SignupUserService.java

private void saveStop(JsonObject jsonDay, Pedestrian ped, int day, String personalId, String tagName,
        String inout) {//from w  w  w.  j  a  va 2 s.c o m
    JsonObject stopIn = jsonDay.getAsJsonObject(tagName);
    JsonElement lat = stopIn.get("lat");
    JsonElement lon = stopIn.get("lon");

    Stop stop = new Stop();

    stop.setDay(day + 1);

    if (inout.equalsIgnoreCase("in"))
        stop.setInout(0);
    else
        stop.setInout(1);

    stop.setLat(lat.getAsDouble());
    stop.setLon(lon.getAsDouble());

    stopDAO.save(stop);
    stop = stopDAO.getLastStop();
    pedDAO.newStop(ped.getPedestrianId(), stop.getStopId());
}

From source file:com.shared.rides.service.SignupUserService.java

private void saveTrack(JsonObject jsonDay, Driver driver, int day, String personalId, String tagName,
        String inout) {//from  ww w .ja  v  a  2  s .co  m
    JsonArray trackArray = jsonDay.getAsJsonArray(tagName);
    Double[][] markers = new Double[trackArray.size()][2];
    JsonElement lat;
    JsonElement lon;

    for (int j = 0; j < trackArray.size(); j++) {
        JsonObject trk = (JsonObject) trackArray.get(j);
        lat = trk.get("lat");
        lon = trk.get("lon");
        markers[j][0] = lat.getAsDouble();
        markers[j][1] = lon.getAsDouble();
    }

    Track track = new Track();
    //El nombre del archivo esta formado por el identificador personal del usuario, mas el dia de semana que es y si es in o out 
    String fileName = personalId + "_" + day + "_" + inout;

    String pathFile = context.getInitParameter("gpx-upload");

    CreateGPXFile.createGPX(fileName, markers, pathFile);
    track.setPathFile(fileName);
    track.setDay(day + 1);
    if (inout.equalsIgnoreCase("in"))
        track.setInout(0);
    else
        track.setInout(1);

    trackDAO.save(track);
    track = trackDAO.getLastTrack();
    driverDAO.newTrack(driver.getDriverId(), track.getTrackId());
}

From source file:com.sixt.service.framework.protobuf.ProtobufUtil.java

License:Apache License

private static Object parseField(Descriptors.FieldDescriptor field, JsonElement value,
        Message.Builder enclosingBuilder) throws Exception {
    switch (field.getType()) {
    case DOUBLE:/*from w  ww  .  j a v a  2  s.c o  m*/
        if (!value.isJsonPrimitive()) {
            // fail;
        }
        return value.getAsDouble();
    case FLOAT:
        if (!value.isJsonPrimitive()) {
            // fail;
        }
        return value.getAsFloat();
    case INT64:
    case UINT64:
    case FIXED64:
    case SINT64:
    case SFIXED64:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsLong();
    case INT32:
    case UINT32:
    case FIXED32:
    case SINT32:
    case SFIXED32:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsInt();
    case BOOL:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsBoolean();
    case STRING:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return value.getAsString();
    case GROUP:
    case MESSAGE:
        if (!value.isJsonObject()) {
            // fail
        }
        return fromJson(enclosingBuilder.newBuilderForField(field), value.getAsJsonObject());
    case BYTES:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        return ByteString.copyFrom(BaseEncoding.base64().decode(value.getAsString()));
    case ENUM:
        if (!value.isJsonPrimitive()) {
            // fail
        }
        String protoEnumValue = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, value.getAsString());
        return field.getEnumType().findValueByName(protoEnumValue);
    }
    return null;
}

From source file:com.sldeditor.exportdata.esri.label.LabelEngineLayerProperties.java

License:Open Source License

/**
 * Extract double.//from www .  j  a va2  s. c  o m
 *
 * @param jsonObj the json obj
 * @param field the field
 * @return the double
 */
private double extractDouble(JsonObject jsonObj, String field) {
    double value = 0.0;

    if (jsonObj != null) {
        JsonElement element = jsonObj.get(field);
        if (element != null) {
            value = element.getAsDouble();
        }
    }
    return value;
}