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:org.apache.giraph.master.BspServiceMaster.java

/**
 * Collect and aggregate the worker statistics for a particular superstep.
 *
 * @param superstep Superstep to aggregate on
 * @return Global statistics aggregated on all worker statistics
 *///from  w  ww.j av  a2  s. c om
private GlobalStats aggregateWorkerStats(long superstep) {
    ImmutableClassesGiraphConfiguration conf = getConfiguration();

    Class<? extends PartitionStats> partitionStatsClass = masterGraphPartitioner.createPartitionStats()
            .getClass();
    GlobalStats globalStats = new GlobalStats();
    // Get the stats from the all the worker selected nodes
    String workerFinishedPath = getWorkerFinishedPath(getApplicationAttempt(), superstep);
    List<String> workerFinishedPathList = null;
    try {
        workerFinishedPathList = getZkExt().getChildrenExt(workerFinishedPath, false, false, true);
    } catch (KeeperException e) {
        throw new IllegalStateException("aggregateWorkerStats: KeeperException", e);
    } catch (InterruptedException e) {
        throw new IllegalStateException("aggregateWorkerStats: InterruptedException", e);
    }

    AggregatedMetrics aggregatedMetrics = new AggregatedMetrics();

    allPartitionStatsList.clear();
    for (String finishedPath : workerFinishedPathList) {
        String hostnamePartitionId = FilenameUtils.getName(finishedPath);
        JSONObject workerFinishedInfoObj = null;
        try {
            byte[] zkData = getZkExt().getData(finishedPath, false, null);
            workerFinishedInfoObj = new JSONObject(new String(zkData, Charset.defaultCharset()));
            List<PartitionStats> statsList = WritableUtils.readListFieldsFromByteArray(
                    Base64.decode(workerFinishedInfoObj.getString(JSONOBJ_PARTITION_STATS_KEY)),
                    partitionStatsClass, conf);
            for (PartitionStats partitionStats : statsList) {
                globalStats.addPartitionStats(partitionStats);
                allPartitionStatsList.add(partitionStats);
            }
            globalStats.addMessageCount(workerFinishedInfoObj.getLong(JSONOBJ_NUM_MESSAGES_KEY));
            globalStats.addMessageBytesCount(workerFinishedInfoObj.getLong(JSONOBJ_NUM_MESSAGE_BYTES_KEY));
            if (conf.metricsEnabled() && workerFinishedInfoObj.has(JSONOBJ_METRICS_KEY)) {
                WorkerSuperstepMetrics workerMetrics = new WorkerSuperstepMetrics();
                WritableUtils.readFieldsFromByteArray(
                        Base64.decode(workerFinishedInfoObj.getString(JSONOBJ_METRICS_KEY)), workerMetrics);
                aggregatedMetrics.add(workerMetrics, hostnamePartitionId);
            }
        } catch (JSONException e) {
            throw new IllegalStateException("aggregateWorkerStats: JSONException", e);
        } catch (KeeperException e) {
            throw new IllegalStateException("aggregateWorkerStats: KeeperException", e);
        } catch (InterruptedException e) {
            throw new IllegalStateException("aggregateWorkerStats: InterruptedException", e);
        } catch (IOException e) {
            throw new IllegalStateException("aggregateWorkerStats: IOException", e);
        }
    }

    if (conf.metricsEnabled()) {
        if (GiraphConstants.METRICS_DIRECTORY.isDefaultValue(conf)) {
            aggregatedMetrics.print(superstep, System.err);
        } else {
            printAggregatedMetricsToHDFS(superstep, aggregatedMetrics);
        }
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(
                "aggregateWorkerStats: Aggregation found " + globalStats + " on superstep = " + getSuperstep());
    }
    return globalStats;
}

From source file:com.simas.vc.helpers.Utils.java

/**
 * Convenience method to fetch a long from a {@code JSONObject} or return null if it's not
 * found.//from  ww  w. j a  va2s  .co  m
 * @param obj    JSONObject to look in
 * @param key    String representing the key to look for
 * @return long for the given key or null if it wasn't found
 */
public static Long getLong(JSONObject obj, String key) {
    try {
        return obj.getLong(key);
    } catch (JSONException e) {
        Log.w(TAG, "Error fetching long!", e);
        return null;
    }
}

From source file:uk.ac.imperial.presage2.web.SimulationServlet.java

/**
 * REST CREATE simulation/*from w w  w.  ja  v  a 2s .  c  o  m*/
 */
@Override
protected synchronized void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    logRequest(req);
    try {
        // parse posted simulation json object
        JSONObject request = new JSONObject(new JSONTokener(req.getReader()));
        // validate data
        String name = request.getString("name");
        String classname = request.getString("classname");
        String state = request.getString("state");
        int finishTime = request.getInt("finishTime");
        PersistentSimulation sim = sto.createSimulation(name, classname, state, finishTime);
        resp.setStatus(201);
        if (!state.equalsIgnoreCase("GROUP")) {
            // add finishTime as a parameter
            sim.addParameter("finishTime", Integer.toString(finishTime));
        }
        if (request.has("parameters")) {
            JSONObject parameters = request.getJSONObject("parameters");
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = parameters.keys(); iterator.hasNext();) {
                String key = (String) iterator.next();
                sim.addParameter(key, parameters.getString(key));
            }
        }
        // set simulation parent
        if (request.has("parent")) {
            try {
                long parentId = request.getLong("parent");
                PersistentSimulation parent = sto.getSimulationById(parentId);
                if (parent != null)
                    sim.setParentSimulation(parent);
            } catch (JSONException e) {
                // ignore non number parent.
            }
        }

        // clear sim cache
        this.cachedSimulations = null;

        // return created simulation object
        JSONObject response = new JSONObject();
        response.put("success", true);
        response.put("message", "Created simulation");
        response.put("data", simulationToJSON(sim));
        resp.getWriter().write(response.toString());
    } catch (JSONException e) {
        // bad request
        resp.setStatus(400);
        logger.warn("Couldn't create new simulation", e);
    }
}

From source file:uk.ac.imperial.presage2.web.SimulationServlet.java

/**
 * REST UPDATE simulation/*from  ww  w.  j  a  va2s . c  om*/
 */
@Override
protected synchronized void doPut(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    logRequest(req);
    String path = req.getPathInfo();
    Matcher matcher = ID_REGEX.matcher(path);
    if (matcher.matches()) {
        long simId = Integer.parseInt(matcher.group(1));
        try {
            // get data sent to us
            JSONObject input = new JSONObject(new JSONTokener(req.getReader()));
            // validate fields
            if (Integer.parseInt(input.get("id").toString()) != simId || input.getString("state").length() < 1
                    || input.getInt("currentTime") < 0 || input.getInt("finishTime") < 0) {
                resp.setStatus(400);
                return;
            }

            PersistentSimulation sim = sto.getSimulationById(simId);
            String state = input.getString("state");
            if (!(sim.getState().equals(state))) {
                sim.setState(state);
            }
            int currentTime = input.getInt("currentTime");
            if (!(sim.getCurrentTime() == currentTime)) {
                sim.setCurrentTime(currentTime);
            }
            int finishTime = input.getInt("finishTime");
            if (!(sim.getFinishTime() == finishTime)) {
                sim.setCurrentTime(finishTime);
            }
            JSONObject parameters = input.getJSONObject("parameters");
            for (@SuppressWarnings("unchecked")
            Iterator<String> iterator = parameters.keys(); iterator.hasNext();) {
                String key = (String) iterator.next();
                sim.addParameter(key, parameters.getString(key));
            }
            // parent simulation
            try {
                long parentId = input.getLong("parent");
                PersistentSimulation parent = sim.getParentSimulation();
                if (parentId == 0 && parent != null) {
                    sim.setParentSimulation(null);
                } else if (parentId > 0 && parent.getID() != parentId) {
                    parent = sto.getSimulationById(parentId);
                    if (parent != null) {
                        sim.setParentSimulation(parent);
                    }
                }
            } catch (JSONException e) {
            }

            JSONObject response = new JSONObject();
            response.put("success", true);
            response.put("data", simulationToJSON(sim));
            resp.getWriter().write(response.toString());
            // clear sim cache
            this.cachedSimulations = null;
        } catch (JSONException e) {
            resp.setStatus(400);
        }
    } else {
        resp.setStatus(400);
    }
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

private String _findModel(String val) {
    LinkedList<Long> ids = new LinkedList<Long>();
    val = val.toLowerCase();
    try {/*w ww .  ja  va 2  s  . co  m*/
        for (JSONObject m : mCol.getModels().all()) {
            if (m.getString("name").toLowerCase().equals(val)) {
                ids.add(m.getLong("id"));
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return "n.mid in " + Utils.ids2str(ids);
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

public String _findDeck(String val) {
    // if searching for all decks, skip
    if (val.equals("*")) {
        return "skip";
        // deck types
    } else if (val.equals("filtered")) {
        return "c.odid";
    }//from w ww  .j  av a2 s .  co  m

    List<Long> ids = null;
    // current deck?
    try {
        if (val.toLowerCase().equals("current")) {
            ids = dids(mCol.getDecks().current().getLong("id"));
        } else if (!val.contains("*")) {
            // single deck
            ids = dids(mCol.getDecks().id(val, false));
        } else {
            // widlcard
            ids = new ArrayList<Long>();
            val = val.replace("*", ".*");
            for (JSONObject d : mCol.getDecks().all()) {
                if (d.getString("name").matches("(?i)" + val)) {
                    for (long id : dids(d.getLong("id"))) {
                        ids.add(id);
                    }
                }
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (ids == null || ids.size() == 0) {
        return "";
    }
    String sids = Utils.ids2str(ids);
    return "c.did in " + sids + " or c.odid in " + sids;
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

private String _findTemplate(String val) {
    // were we given an ordinal number?
    Integer num = null;/*  ww  w  .j  a  va 2s. co m*/
    try {
        num = Integer.parseInt(val) - 1;
    } catch (NumberFormatException e) {
        num = null;
    }
    if (num != null) {
        return "c.ord = " + num;
    }
    // search for template names
    List<String> lims = new ArrayList<String>();
    try {
        for (JSONObject m : mCol.getModels().all()) {
            JSONArray tmpls = m.getJSONArray("tmpls");
            for (int ti = 0; ti < tmpls.length(); ++ti) {
                JSONObject t = tmpls.getJSONObject(ti);
                if (t.getString("name").equalsIgnoreCase(val)) {
                    if (m.getInt("type") == Sched.MODEL_CLOZE) {
                        // if the user has asked for a cloze card, we want
                        // to give all ordinals, so we just limit to the
                        // model instead
                        lims.add("(n.mid = " + m.getLong("id") + ")");
                    } else {
                        lims.add("(n.mid = " + m.getLong("id") + " and c.ord = " + t.getInt("ord") + ")");
                    }
                }
            }

        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return Utils.join(" or ", lims.toArray(new String[] {}));
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

private String _findField(String field, String val) {
    val = val.replace("*", "%");
    // find models that have that field
    Map<Long, Object[]> mods = new HashMap<Long, Object[]>();
    try {/* www. j a v a  2  s .  c o m*/
        for (JSONObject m : mCol.getModels().all()) {
            JSONArray flds = m.getJSONArray("flds");
            for (int fi = 0; fi < flds.length(); ++fi) {
                JSONObject f = flds.getJSONObject(fi);
                if (f.getString("name").equalsIgnoreCase(field)) {
                    mods.put(m.getLong("id"), new Object[] { m, f.getInt("ord") });
                }

            }

        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    if (mods.isEmpty()) {
        // nothing has that field
        return "";
    }
    // gather nids
    // Pattern.quote escapes the meta characters with \Q \E
    String regex = Pattern.quote(val).replace("\\Q_\\E", ".").replace("\\Q%\\E", ".*");
    LinkedList<Long> nids = new LinkedList<Long>();
    Cursor cur = null;
    try {
        cur = mCol.getDb().getDatabase()
                .rawQuery("select id, mid, flds from notes where mid in "
                        + Utils.ids2str(new LinkedList<Long>(mods.keySet())) + " and flds like ? escape '\\'",
                        new String[] { "%" + val + "%" });
        while (cur.moveToNext()) {
            String[] flds = Utils.splitFields(cur.getString(2));
            int ord = (Integer) mods.get(cur.getLong(1))[1];
            String strg = flds[ord];
            if (Pattern.compile(regex, Pattern.CASE_INSENSITIVE).matcher(strg).matches()) {
                nids.add(cur.getLong(0));
            }
        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (nids.isEmpty()) {
        return "";
    }
    return "n.id in " + Utils.ids2str(nids);
}

From source file:com.hichinaschool.flashcards.libanki.Finder.java

public static int findReplace(Collection col, List<Long> nids, String src, String dst, boolean isRegex,
        String field, boolean fold) {
    Map<Long, Integer> mmap = new HashMap<Long, Integer>();
    if (field != null) {
        try {//  ww w  . ja va2 s  .  co  m
            for (JSONObject m : col.getModels().all()) {
                JSONArray flds = m.getJSONArray("flds");
                for (int fi = 0; fi < flds.length(); ++fi) {
                    JSONObject f = flds.getJSONObject(fi);
                    if (f.getString("name").equals(field)) {
                        mmap.put(m.getLong("id"), f.getInt("ord"));
                    }
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        if (mmap.isEmpty()) {
            return 0;
        }
    }
    // find and gather replacements
    if (!isRegex) {
        src = Pattern.quote(src);
    }
    if (fold) {
        src = "(?i)" + src;
    }
    Pattern regex = Pattern.compile(src);

    ArrayList<Object[]> d = new ArrayList<Object[]>();
    String sql = "select id, mid, flds from notes where id in " + Utils.ids2str(nids.toArray(new Long[] {}));
    nids = new ArrayList<Long>();

    Cursor cur = null;
    try {
        cur = col.getDb().getDatabase().rawQuery(sql, null);
        while (cur.moveToNext()) {
            String flds = cur.getString(2);
            String origFlds = flds;
            // does it match?
            String[] sflds = Utils.splitFields(flds);
            if (field != null) {
                long mid = cur.getLong(1);
                if (!mmap.containsKey(mid)) {
                    continue;
                }
                int ord = mmap.get(mid);
                sflds[ord] = regex.matcher(sflds[ord]).replaceAll(dst);
            } else {
                for (int i = 0; i < sflds.length; ++i) {
                    sflds[i] = regex.matcher(sflds[i]).replaceAll(dst);
                }
            }
            flds = Utils.joinFields(sflds);
            if (!flds.equals(origFlds)) {
                long nid = cur.getLong(0);
                nids.add(nid);
                d.add(new Object[] { flds, Utils.intNow(), col.usn(), nid });
            }

        }
    } finally {
        if (cur != null) {
            cur.close();
        }
    }
    if (d.isEmpty()) {
        return 0;
    }
    // replace
    col.getDb().executeMany("update notes set flds=?,mod=?,usn=? where id=?", d);
    long[] pnids = Utils.toPrimitive(nids);
    col.updateFieldCache(pnids);
    col.genCards(pnids);
    return d.size();
}

From source file:net.solosky.litefetion.LiteFetion.java

/**
 * ??/*from  w  ww  . j av  a 2  s .co m*/
 */
private ActionResult retirePersonalInfo() {
    try {
        HttpRequest request = this.createActionHttpRequest(Settings.WEBIM_URL_GET_PERSONAL_INFO);
        HttpResponse response = this.client.tryExecute(request, Settings.FEITON_MAX_REQUEST_EXECUTE_TIMES);
        JSONObject json = new JSONObject(response.getResponseString());
        if (json.getInt("rc") == 200) {

            json = json.getJSONObject("rv");
            user.setMobile(json.getLong("mn"));
            user.setNickName(json.getString("nn"));
            user.setUri(json.getString("uri"));
            user.setSid(json.getInt("sid"));
            user.setUserId(json.getInt("uid"));
            user.setImpresa(json.getString("i"));

            return ActionResult.SUCCESS;
        } else {
            return ActionResult.REQUEST_FAILED;
        }
    } catch (IOException e) {
        return ActionResult.HTTP_FAILED;
    } catch (JSONException e) {
        return ActionResult.JSON_FAILED;
    }
}