Example usage for org.json JSONObject getLong

List of usage examples for org.json JSONObject getLong

Introduction

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

Prototype

public long getLong(String key) throws JSONException 

Source Link

Document

Get the long value associated with a key.

Usage

From source file:com.github.mhendred.face4j.model.UserStatus.java

public UserStatus(final JSONObject jObj) throws JSONException {
    uid = jObj.getString("uid");
    training_set_size = jObj.getInt("training_set_size");
    last_trained = jObj.getLong("last_trained");
    training_in_progress = jObj.getBoolean("training_in_progress");
}

From source file:org.sleeksnap.impl.HistoryEntry.java

/**
 * Constructs a new HistoryEntry object from the specified JSON Object
 * /*from w w  w .java 2 s  .  c  om*/
 * @param object
 *            The JSON Object to read from
 */
public HistoryEntry(final JSONObject object) {
    this(object.getString("url"), object.getString("uploader"), new Date(object.getLong("date")));
}

From source file:org.archive.modules.Processor.java

/**
 * Restore internal state from JSONObject stored at earlier
 * checkpoint-time./*from w ww.  j  a va  2s . c  o m*/
 * 
 * @param json JSONObject
 * @throws JSONException
 */
protected void fromCheckpointJson(JSONObject json) throws JSONException {
    uriCount.set(json.getLong("uriCount"));
}

From source file:fr.haploid.webservices.WebServicesTask.java

public WebServicesTask(CobaltFragment fragment, JSONObject call) {
    mFragment = fragment;//from w  w w. j  ava2 s . c o  m
    mCall = call;

    try {
        mCallId = call.getLong(kJSCallId);
        JSONObject data = call.getJSONObject(Cobalt.kJSData);
        mSendCacheResult = data.optBoolean(kJSSendCacheResult);
        mUrl = data.optString(kJSUrl, null);

        if (mUrl != null) {
            mHeaders = data.optJSONObject(kJSHeaders);
            mParams = data.optString(kJSParams);
            mTimeout = data.optInt(kJSTimeout, -1);
            mType = data.getString(kJSType);
            mSaveToStorage = data.optBoolean(kJSSaveToStorage);
        }

        if (mSendCacheResult || mUrl != null)
            mProcessData = data.optJSONObject(kJSProcessData);

        if (mSendCacheResult || (mUrl != null && mSaveToStorage)) {
            mStorageKey = data.getString(kJSStorageKey);
        }
    } catch (JSONException exception) {
        if (Cobalt.DEBUG) {
            Log.e(WebServicesPlugin.TAG, TAG + ": check your Webservice call. Known issues: \n"
                    + "\t- missing data field, \n" + "\t- url field is defined but but missing type field, \n"
                    + "\t- sendCacheResult field is true or url field is defined and saveToStorage field is true but missing storageKey field.\n");
            exception.printStackTrace();
        }
    }
}

From source file:fr.qinder.tools.JSON.java

/**
 * Get value of the key from a JSONObject. If the key not exists in the
 * JSONObject, defValue is return.//from   ww w.  java  2s.  co m
 * 
 * @param obj
 *            JSONObject for getting the value
 * @param key
 *            String of the key
 * @param defValue
 *            Default value if key not exists
 * @return The value if key exist, defValue else
 */
@SuppressWarnings("unchecked")
private static <T> T getValue(JSONObject obj, String key, T defValue) throws JSONException {
    T res = defValue;
    if (defValue instanceof Double) {
        res = (T) ((Double) obj.getDouble(key));
    } else if (defValue instanceof Integer) {
        res = (T) ((Integer) obj.getInt(key));
    } else if (defValue instanceof Boolean) {
        res = (T) ((Boolean) obj.getBoolean(key));
    } else if (defValue instanceof Long) {
        res = (T) ((Long) obj.getLong(key));
    } else if (defValue instanceof String) {
        res = (T) obj.getString(key);
    } else if (defValue instanceof JSONObject) {
        res = (T) obj.getJSONObject(key);
    } else if (defValue instanceof JSONArray) {
        res = (T) obj.getJSONArray(key);
    }
    return res;
}

From source file:com.nextgis.maplib.datasource.ngw.Resource.java

public Resource(JSONObject json, Connection connection) {

    mConnection = connection;/*from   w w w.  j a v a2  s. co m*/
    try {
        JSONObject JSONResource = json.getJSONObject("resource");

        mHasChildren = JSONResource.getBoolean("children");
        if (JSONResource.has("description"))
            mDescription = JSONResource.getString("description");

        mName = JSONResource.getString("display_name");
        mRemoteId = JSONResource.getLong("id");
        mType = mConnection.getType(JSONResource.getString("cls"));

        if (JSONResource.has("keyname"))
            mKeyName = JSONResource.getString("keyname");
        if (JSONResource.has("owner_user")) {
            JSONObject jsonObjectOwnerUser = JSONResource.getJSONObject("owner_user");
            if (jsonObjectOwnerUser.has("id"))
                mOwnerId = jsonObjectOwnerUser.getLong("id");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mId = Connections.getNewId();
}

From source file:com.graphhopper.http.GraphHopperWeb.java

@Override
public GHResponse route(GHRequest request) {
    StopWatch sw = new StopWatch().start();
    double took = 0;
    try {//from   w ww.jav a2s  . co  m
        String places = "";
        for (GHPoint p : request.getPoints()) {
            places += "point=" + p.lat + "," + p.lon + "&";
        }

        String url = serviceUrl + "?" + places + "&type=json" + "&points_encoded=" + pointsEncoded
                + "&min_path_precision=" + request.getHint("douglas.minprecision", 1) + "&algo="
                + request.getAlgorithm() + "&locale=" + request.getLocale().toString() + "&elevation="
                + withElevation;

        if (!request.getVehicle().isEmpty())
            url += "&vehicle=" + request.getVehicle();

        if (!key.isEmpty())
            url += "&key=" + key;

        String str = downloader.downloadAsString(url);
        JSONObject json = new JSONObject(str);
        GHResponse res = new GHResponse();

        if (json.getJSONObject("info").has("errors")) {
            JSONArray errors = json.getJSONObject("info").getJSONArray("errors");

            for (int i = 0; i < errors.length(); i++) {
                JSONObject error = errors.getJSONObject(i);
                String exClass = error.getString("details");
                String exMessage = error.getString("message");

                if (exClass.equals(UnsupportedOperationException.class.getName())) {
                    res.addError(new UnsupportedOperationException(exMessage));
                } else if (exClass.equals(IllegalStateException.class.getName())) {
                    res.addError(new IllegalStateException(exMessage));
                } else if (exClass.equals(RuntimeException.class.getName())) {
                    res.addError(new RuntimeException(exMessage));
                } else if (exClass.equals(IllegalArgumentException.class.getName())) {
                    res.addError(new IllegalArgumentException(exMessage));
                } else {
                    res.addError(new Exception(exClass + " " + exMessage));
                }
            }

            return res;

        } else {
            took = json.getJSONObject("info").getDouble("took");
            JSONArray paths = json.getJSONArray("paths");
            JSONObject firstPath = paths.getJSONObject(0);
            double distance = firstPath.getDouble("distance");
            int time = firstPath.getInt("time");
            PointList pointList;
            if (pointsEncoded) {
                String pointStr = firstPath.getString("points");
                pointList = WebHelper.decodePolyline(pointStr, 100, withElevation);
            } else {
                JSONArray coords = firstPath.getJSONObject("points").getJSONArray("coordinates");
                pointList = new PointList(coords.length(), withElevation);
                for (int i = 0; i < coords.length(); i++) {
                    JSONArray arr = coords.getJSONArray(i);
                    double lon = arr.getDouble(0);
                    double lat = arr.getDouble(1);
                    if (withElevation)
                        pointList.add(lat, lon, arr.getDouble(2));
                    else
                        pointList.add(lat, lon);
                }
            }

            if (instructions) {
                JSONArray instrArr = firstPath.getJSONArray("instructions");

                InstructionList il = new InstructionList(trMap.getWithFallBack(request.getLocale()));
                for (int instrIndex = 0; instrIndex < instrArr.length(); instrIndex++) {
                    JSONObject jsonObj = instrArr.getJSONObject(instrIndex);
                    double instDist = jsonObj.getDouble("distance");
                    String text = jsonObj.getString("text");
                    long instTime = jsonObj.getLong("time");
                    int sign = jsonObj.getInt("sign");
                    JSONArray iv = jsonObj.getJSONArray("interval");
                    int from = iv.getInt(0);
                    int to = iv.getInt(1);
                    PointList instPL = new PointList(to - from, withElevation);
                    for (int j = from; j <= to; j++) {
                        instPL.add(pointList, j);
                    }

                    // TODO way and payment type
                    Instruction instr = new Instruction(sign, text, InstructionAnnotation.EMPTY, instPL)
                            .setDistance(instDist).setTime(instTime);
                    il.add(instr);
                }
                res.setInstructions(il);
            }
            return res.setPoints(pointList).setDistance(distance).setMillis(time);
        }
    } catch (Exception ex) {
        throw new RuntimeException(
                "Problem while fetching path " + request.getPoints() + ": " + ex.getMessage(), ex);
    } finally {
        logger.debug("Full request took:" + sw.stop().getSeconds() + ", API took:" + took);
    }
}

From source file:com.oakesville.mythling.util.MythTvParser.java

private LiveStreamInfo buildLiveStream(JSONObject obj) throws JSONException {
    LiveStreamInfo streamInfo = new LiveStreamInfo();

    if (obj.has("Id"))
        streamInfo.setId(obj.getLong("Id"));
    if (obj.has("StatusInt"))
        streamInfo.setStatusCode(obj.getInt("StatusInt"));
    if (obj.has("StatusStr"))
        streamInfo.setStatus(obj.getString("StatusStr"));
    if (obj.has("StatusMessage"))
        streamInfo.setMessage(obj.getString("StatusMessage"));
    if (obj.has("PercentComplete"))
        streamInfo.setPercentComplete(obj.getInt("PercentComplete"));
    if (obj.has("RelativeURL"))
        streamInfo.setRelativeUrl(obj.getString("RelativeURL").replaceAll(" ", "%20"));
    if (obj.has("SourceFile"))
        streamInfo.setFile(obj.getString("SourceFile"));
    if (obj.has("Width"))
        streamInfo.setWidth(obj.getInt("Width"));
    if (obj.has("Height"))
        streamInfo.setHeight(obj.getInt("Height"));
    if (obj.has("Bitrate"))
        streamInfo.setVideoBitrate(obj.getInt("Bitrate"));
    if (obj.has("AudioBitrate"))
        streamInfo.setAudioBitrate(obj.getInt("AudioBitrate"));

    return streamInfo;
}

From source file:edu.umass.cs.gigapaxos.paxospackets.RequestPacket.java

public static boolean addDebugInfo(JSONObject msg, String str, int nodeID) throws JSONException {
    boolean added = false;
    if (DEBUG && msg.has(Keys.DBG.toString()) && msg.has(Keys.CT.toString())) {
        str = str + nodeID;//from  w w w  .j a va 2 s  . c  o  m
        String debug = msg.getString(Keys.DBG.toString()) + makeDebugInfo(str, msg.getLong(Keys.CT.toString()));
        added = true;
        msg.put(Keys.DBG.toString(), debug);
    }
    return added;
}

From source file:edu.umass.cs.gigapaxos.paxospackets.RequestPacket.java

public RequestPacket(JSONObject json) throws JSONException {
    super(json);/*from   w  ww  . j ava2  s.  c o  m*/
    this.packetType = PaxosPacketType.REQUEST;
    this.stop = json.optBoolean(Keys.STOP.toString());
    this.requestID = json.getLong(Keys.QID.toString());
    this.requestValue = json.getString(Keys.QV.toString());

    this.responseValue = json.has(Keys.RV.toString()) ? json.getString(Keys.RV.toString()) : null;
    this.entryTime = json.getLong(Keys.ET.toString());
    this.forwardCount = (json.has(Keys.NFWDS.toString()) ? json.getInt(Keys.NFWDS.toString()) : 0);
    this.forwarderID = (json.has(RequestPacket.Keys.FWDR.toString())
            ? json.getInt(RequestPacket.Keys.FWDR.toString())
            : IntegerMap.NULL_INT_NODE);
    this.debugInfo = (json.has(Keys.DBG.toString()) ? json.getString(Keys.DBG.toString()) : "");

    this.clientAddress = (json.has(Keys.CA.toString())
            ? Util.getInetSocketAddressFromString(json.getString(Keys.CA.toString()))
            : JSONNIOTransport.getSenderAddress(json));
    this.listenAddress = (json.has(Keys.LA.toString())
            ? Util.getInetSocketAddressFromString(json.getString(Keys.LA.toString()))
            : JSONNIOTransport.getReceiverAddress(json));

    this.entryReplica = json.getInt(PaxosPacket.NodeIDKeys.E.toString());
    this.shouldReturnRequestValue = json.optBoolean(Keys.QF.toString());

    // unwrap latched along batch
    JSONArray batchedJSON = json.has(Keys.BATCH.toString()) ? json.getJSONArray(Keys.BATCH.toString()) : null;
    if (batchedJSON != null && batchedJSON.length() > 0) {
        this.batched = new RequestPacket[batchedJSON.length()];
        for (int i = 0; i < batchedJSON.length(); i++) {
            this.batched[i] = new RequestPacket((JSONObject) batchedJSON.get(i)
            // new JSONObject(batchedJSON.getString(i))
            );
        }
    }

    // we remembered the original string for recalling here
    this.stringifiedSelf = json.has(Keys.STRINGIFIED.toString())
            ? (String) json.get(Keys.STRINGIFIED.toString())
            : null;

    if (json.has(Keys.BC.toString()))
        this.broadcasted = json.getBoolean(Keys.BC.toString());
    if (json.has(Keys.DIG.toString()))
        try {
            this.digest = json.getString(Keys.DIG.toString()).getBytes(CHARSET);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
}