Example usage for org.json JSONObject optDouble

List of usage examples for org.json JSONObject optDouble

Introduction

In this page you can find the example usage for org.json JSONObject optDouble.

Prototype

public double optDouble(String key) 

Source Link

Document

Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number.

Usage

From source file:org.obiba.magma.Coordinate.java

private static double getKeyValue(String[] keyList, JSONObject object) {
    double value = 0;

    for (String key : keyList) {
        value = object.optDouble(key);
        if (!isNaN(value)) {
            break;
        }/*  www  . j  a v a2s . c o m*/
    }
    if (isNaN(value)) {
        throw new MagmaRuntimeException("The latitude or the longitude is not defined");
    }
    return value;
}

From source file:com.basetechnology.s0.agentserver.field.MoneyField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("money"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    double defaultValue = fieldJson.has("default_value") ? fieldJson.optDouble("default_value") : 0;
    double minValue = fieldJson.has("min_value") ? fieldJson.optDouble("min_value") : Double.MIN_VALUE;
    double maxValue = fieldJson.has("max_value") ? fieldJson.optDouble("max_value") : Double.MAX_VALUE;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new MoneyField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth,
            compute);/* ww  w .  jav a2  s.c  om*/
}

From source file:edu.asu.bscs.ihattend.jsonrpcapp.JsonRPCCalculator.java

public Double calculate(Double op1, Double op2, String operation) {
    try {/*  w  w w. jav a 2  s .  c o m*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("jsonrpc", "2.0");
        jsonObject.put("id", ++id);
        jsonObject.put("method", operation);

        String params = String.format(",\"params\":[%.2f,%.2f]", op1, op2);
        String almost = jsonObject.toString();
        String begin = almost.substring(0, almost.length() - 1);
        String end = almost.substring(almost.length() - 1);
        String call = begin + params + end;

        Log.d(TAG, "call: " + call);
        String responseString = server.call(call);
        Log.d(TAG, "response: " + responseString);
        JSONObject response = new JSONObject(responseString);
        Double result = response.optDouble("result");
        Log.d(TAG, "result: " + result);

        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    // should really throw an exception...
    return 0.0;
}

From source file:com.kimkha.finanvita.billing.SkuDetails.java

public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException {
    mItemType = itemType;/*from  w w  w.  j a  v a2  s  . com*/
    mJson = jsonSkuDetails;
    JSONObject o = new JSONObject(mJson);
    mSku = o.optString("productId");
    mType = o.optString("type");
    mPrice = o.optString("price");
    mPriceAmount = o.optDouble("price_amount_micros") / 1000000;
    mTitle = o.optString("title");
    mDescription = o.optString("description");
    mCurrency = o.optString("price_currency_code");
}

From source file:com.findcab.driver.object.DriverInfo.java

public DriverInfo(JSONObject jObject) {

    car_license = jObject.optString("car_license");
    car_service_number = jObject.optString("car_service_number");
    car_type = jObject.optString("car_type");
    distance = jObject.optDouble("distance");
    id = jObject.optInt("id");
    lat = jObject.optDouble("lat");
    lng = jObject.optDouble("lng");
    mobile = jObject.optString("mobile");
    name = jObject.optString("name");
    password = jObject.optString("password");
    rate = jObject.optInt("rate");
    updated_at = jObject.optString("updated_at");

}

From source file:com.basetechnology.s0.agentserver.field.FloatField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("float"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    double defaultValue = fieldJson.has("default_value") ? fieldJson.optDouble("default_value") : 0;
    double minValue = fieldJson.has("min_value") ? fieldJson.optDouble("min_value") : Double.MIN_VALUE;
    double maxValue = fieldJson.has("max_value") ? fieldJson.optDouble("max_value") : Double.MAX_VALUE;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new FloatField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth,
            compute);// www . j a v a  2 s  .  com
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse value.//from   w  w  w.  jav  a  2 s. c o m
 * 
 * @param jsonFolder
 * @return
 */
protected static Value parseValue(JSONObject jsonValue) {
    Value res = new Value();
    if (jsonValue != null) {
        double val = jsonValue.optDouble("startOfPeriod");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setStartOfPeriod(val);
        val = jsonValue.optDouble("credit");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setCredit(val);
        val = jsonValue.optDouble("debit");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setDebit(val);
        val = jsonValue.optDouble("endOfPeriod");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setEndOfPeriod(val);
        val = jsonValue.optDouble("control");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setControl(val);
        if (jsonValue.optString("manual").equals("y")) {
            res.setManual(true);
        }
    }
    return res;
}

From source file:org.chromium.ChromeNotifications.java

private void makeNotification(final CordovaArgs args) throws JSONException {
    String notificationId = args.getString(0);
    JSONObject options = args.getJSONObject(1);
    Resources resources = cordova.getActivity().getResources();
    Bitmap largeIcon = makeBitmap(options.getString("iconUrl"),
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
            resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height));
    int smallIconId = resources.getIdentifier("notification_icon", "drawable",
            cordova.getActivity().getPackageName());
    if (smallIconId == 0) {
        smallIconId = resources.getIdentifier("icon", "drawable", cordova.getActivity().getPackageName());
    }/*from   w w w  .j a v  a  2  s .c  o  m*/
    NotificationCompat.Builder builder = new NotificationCompat.Builder(cordova.getActivity())
            .setSmallIcon(smallIconId).setContentTitle(options.getString("title"))
            .setContentText(options.getString("message")).setLargeIcon(largeIcon)
            .setPriority(options.optInt("priority"))
            .setContentIntent(makePendingIntent(NOTIFICATION_CLICKED_ACTION, notificationId, -1,
                    PendingIntent.FLAG_CANCEL_CURRENT))
            .setDeleteIntent(makePendingIntent(NOTIFICATION_CLOSED_ACTION, notificationId, -1,
                    PendingIntent.FLAG_CANCEL_CURRENT));
    double eventTime = options.optDouble("eventTime");
    if (eventTime != 0) {
        builder.setWhen(Math.round(eventTime));
    }
    JSONArray buttons = options.optJSONArray("buttons");
    if (buttons != null) {
        for (int i = 0; i < buttons.length(); i++) {
            JSONObject button = buttons.getJSONObject(i);
            builder.addAction(android.R.drawable.ic_dialog_info, button.getString("title"), makePendingIntent(
                    NOTIFICATION_BUTTON_CLICKED_ACTION, notificationId, i, PendingIntent.FLAG_CANCEL_CURRENT));
        }
    }
    String type = options.getString("type");
    Notification notification;
    if ("image".equals(type)) {
        NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle(builder);
        String bigImageUrl = options.optString("imageUrl");
        if (!bigImageUrl.isEmpty()) {
            bigPictureStyle.bigPicture(makeBitmap(bigImageUrl, 0, 0));
        }
        notification = bigPictureStyle.build();
    } else if ("list".equals(type)) {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
        JSONArray items = options.optJSONArray("items");
        if (items != null) {
            for (int i = 0; i < items.length(); i++) {
                JSONObject item = items.getJSONObject(i);
                inboxStyle.addLine(Html.fromHtml("<b>" + item.getString("title")
                        + "</b>&nbsp;&nbsp;&nbsp;&nbsp;" + item.getString("message")));
            }
        }
        notification = inboxStyle.build();
    } else {
        if ("progress".equals(type)) {
            int progress = options.optInt("progress");
            builder.setProgress(100, progress, false);
        }
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle(builder);
        bigTextStyle.bigText(options.getString("message"));
        notification = bigTextStyle.build();
    }
    notificationManager.notify(notificationId.hashCode(), notification);
}

From source file:org.neo4j.mytests.SSShortestPathTest.java

@Test
public void shouldReturnMaxFlow() {
    Transaction tx = db.beginTx();//from  ww  w  .ja v a  2  s  .  co  m
    try {
        Node a = db.createNode();
        Node b = db.createNode();
        Node c = db.createNode();
        Node d = db.createNode();
        Node e = db.createNode();
        a.createRelationshipTo(e, MyRelationshipTypes.KNOWS);
        a.createRelationshipTo(b, MyRelationshipTypes.KNOWS);
        e.createRelationshipTo(b, MyRelationshipTypes.KNOWS);
        e.createRelationshipTo(d, MyRelationshipTypes.KNOWS);
        b.createRelationshipTo(c, MyRelationshipTypes.KNOWS);
        c.createRelationshipTo(d, MyRelationshipTypes.KNOWS);

    } catch (Exception e) {
        System.err.println("Exception Error: MaxflowTest.shouldReturnMaxFlow: " + e);
        tx.failure();
    } finally {
        tx.success();
        tx.close();
    }

    String serverBaseUri = server.baseUri().toString();
    URL uriArray[] = new URL[6];
    String q1 = serverBaseUri + "hintplugin/utils/ssshortestpath/0/2"; // a-c 6
    String q2 = serverBaseUri + "hintplugin/utils/ssshortestpath/0/3"; // a-d 4
    String q3 = serverBaseUri + "hintplugin/utils/ssshortestpath/0/4"; // a-e 2
    String q4 = serverBaseUri + "hintplugin/utils/ssshortestpath/2/3"; // c-d 4
    String q5 = serverBaseUri + "hintplugin/utils/ssshortestpath/2/4"; // c-e 2
    String q6 = serverBaseUri + "hintplugin/utils/ssshortestpath/3/4"; // d-e 2

    try {
        uriArray[0] = new URL(q1);
        uriArray[1] = new URL(q2);
        uriArray[2] = new URL(q3);
        uriArray[3] = new URL(q4);
        uriArray[4] = new URL(q5);
        uriArray[5] = new URL(q6);
    } catch (Exception ex) {
        System.out.println("***** ERROR: " + ex);
    }
    //Establish a connection to the server and get Content.
    for (int i = 0; i < uriArray.length; i++) {
        try {
            HttpURLConnection http = (HttpURLConnection) uriArray[i].openConnection();
            http.setRequestMethod("GET");
            http.connect();
            StringBuffer text = new StringBuffer();
            InputStreamReader in = new InputStreamReader((InputStream) http.getContent());
            BufferedReader buff = new BufferedReader(in);
            String line = "";
            while (line != null) {
                line = buff.readLine();
                text.append(line + " ");
            }
            JSONObject obj = new JSONObject(text.toString());
            System.out.println("***SSSPTH-JSON: " + obj.optDouble("shortestPaths"));
        } catch (Exception ex) {
            System.out.println("MaxflowTest Exception: " + ex);
        }
    }
    assertEquals("200", "200");
}

From source file:com.QuarkLabs.BTCeClient.services.CheckTickersService.java

@Override
protected void onHandleIntent(Intent intent) {

    SharedPreferences sh = PreferenceManager.getDefaultSharedPreferences(this);
    Set<String> x = sh.getStringSet("PairsToDisplay", new HashSet<String>());
    if (x.size() == 0) {
        return;/*from   w  ww  . ja v  a  2  s .co m*/
    }
    String[] pairs = x.toArray(new String[x.size()]);
    ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    String url = BASE_URL;
    for (String xx : pairs) {
        url += xx.replace("/", "_").toLowerCase(Locale.US) + "-";
    }
    SimpleRequest reqSim = new SimpleRequest();

    if (networkInfo != null && networkInfo.isConnected()) {
        JSONObject data = null;
        try {
            data = reqSim.makeRequest(url);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (data != null && data.optInt("success", 1) != 0) {

            ArrayList<Ticker> tickers = new ArrayList<>();
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = data.keys(); iterator.hasNext();) {
                String key = iterator.next();
                JSONObject pairData = data.optJSONObject(key);
                Ticker ticker = new Ticker(key);
                ticker.setUpdated(pairData.optLong("updated"));
                ticker.setAvg(pairData.optDouble("avg"));
                ticker.setBuy(pairData.optDouble("buy"));
                ticker.setSell(pairData.optDouble("sell"));
                ticker.setHigh(pairData.optDouble("high"));
                ticker.setLast(pairData.optDouble("last"));
                ticker.setLow(pairData.optDouble("low"));
                ticker.setVol(pairData.optDouble("vol"));
                ticker.setVolCur(pairData.optDouble("vol_cur"));
                tickers.add(ticker);
            }

            String message = checkNotifiers(tickers, TickersStorage.loadLatestData());

            if (message.length() != 0) {
                NotificationManager notificationManager = (NotificationManager) getSystemService(
                        NOTIFICATION_SERVICE);
                NotificationCompat.Builder nb = new NotificationCompat.Builder(this)
                        .setContentTitle(getResources().getString(R.string.app_name))
                        .setSmallIcon(R.drawable.ic_stat_bitcoin_sign)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentText(message.substring(0, message.length() - 2));
                notificationManager.notify(ConstantHolder.ALARM_NOTIF_ID, nb.build());
            }

            Map<String, Ticker> newData = new HashMap<>();
            for (Ticker ticker : tickers) {
                newData.put(ticker.getPair(), ticker);
            }
            TickersStorage.saveData(newData);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("UpdateTickers"));
        }
    } else {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                //Toast.makeText(CheckTickersService.this, "Unable to fetch data", Toast.LENGTH_SHORT).show();
            }
        });

    }
}