Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

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

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

From source file:com.t2.compassionMeditation.MeditationActivity.java

/**
 * Receives a json string containing data about all of the paired sensors
 * the adds a new BioSensor for each one to the mBioSensors collection
 * /* w w w .j av  a2 s  .co m*/
 * @param jsonString String containing info on all paired devices
 */
private void populateBioSensors(String jsonString) {

    Log.d(TAG, this.getClass().getSimpleName() + " populateBioSensors");
    // Now clear it out and populate it. The only difference is that
    // if a sensor previously existed, then 
    mBioSensors.clear();
    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Boolean enabled = jsonObject.getBoolean("enabled");
            String name = jsonObject.getString("name");
            String address = jsonObject.getString("address");
            int connectionStatus = jsonObject.getInt("connectionStatus");

            if (name.equalsIgnoreCase("system")) {
                mBluetoothEnabled = enabled;
            } else {

                Log.i(TAG, "Adding sensor " + name + ", " + address + (enabled ? ", enabled" : ", disabled")
                        + " : " + Util.connectionStatusToString(connectionStatus));
                BioSensor bioSensor = new BioSensor(name, address, enabled);
                bioSensor.mConnectionStatus = connectionStatus;
                mBioSensors.add(bioSensor);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
}

From source file:com.t2.compassionMeditation.Graphs1Activity.java

/**
 * Receives a json string containing data about all of the paired sensors
 * the adds a new BioSensor for each one to the mBioSensors collection
 * /*from w ww .  jav a  2  s.c  o  m*/
 * @param jsonString String containing info on all paired devices
 */
private void populateBioSensors(String jsonString) {

    Log.d(TAG, this.getClass().getSimpleName() + " populateBioSensors");
    // Now clear it out and populate it. The only difference is that
    // if a sensor previously existed, then 
    mBioSensors.clear();
    try {
        JSONArray jsonArray = new JSONArray(jsonString);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Boolean enabled = jsonObject.getBoolean("enabled");
            String name = jsonObject.getString("name");
            String address = jsonObject.getString("address");
            int connectionStatus = jsonObject.getInt("connectionStatus");

            if (name.equalsIgnoreCase("system")) {
                mBluetoothEnabled = enabled;
            } else {

                Log.d(TAG, "Adding sensor " + name + ", " + address + (enabled ? ", enabled" : ", disabled")
                        + " : " + Util.connectionStatusToString(connectionStatus));
                BioSensor bioSensor = new BioSensor(name, address, enabled);
                bioSensor.mConnectionStatus = connectionStatus;
                mBioSensors.add(bioSensor);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
    }
}

From source file:com.richtodd.android.quiltdesign.block.Swatch.java

static final Swatch createFromJSONObject(JSONObject jsonObject) throws JSONException {

    Swatch swatch = new Swatch();

    swatch.m_color = jsonObject.getInt("color");

    return swatch;
}

From source file:rocks.teammolise.myunimol.webapp.login.LoginServlet.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods./*from   www. ja va2 s.c o  m*/
  *
  * @param request servlet request
  * @param response servlet response
  * @throws ServletException if a servlet-specific error occurs
  * @throws IOException if an I/O error occurs
  */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //il tipo di risultato della servlet
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    ConfigurationManager configManager = ConfigurationManagerHandler.getInstance();

    try {
        //sono per ricavare il contenuto degli input field
        String username = (String) request.getParameter("username");
        String password = (String) request.getParameter("password");

        if (!configManager.isAllowed(username)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Betatest; you are not allowed!");
            return;
        }

        JSONObject loginJSON = new APIConsumer().consume("testCredentials", username, password);

        if (loginJSON.getString("result").equals("failure")) {
            out.print(loginJSON.toString());
        } else {
            //inserisco i dati presi dal JSON nel bean dell'utente
            UserInfo userInfo = new UserInfo();
            userInfo.setName(loginJSON.getString("name"));
            userInfo.setSurname(loginJSON.getString("surname"));
            userInfo.setStudentClass(loginJSON.getString("studentClass"));
            userInfo.setStudentId(loginJSON.getString("studentID"));
            userInfo.setTaxes(loginJSON.getString("taxes"));
            userInfo.setCareerPlan(loginJSON.getString("careerPlan"));
            userInfo.setAvailableExams(loginJSON.getInt("availableExams"));
            userInfo.setEnrolledExams(loginJSON.getInt("enrolledExams"));
            userInfo.setUsername(username);
            userInfo.setPassword(password);

            userInfo.setCourse(loginJSON.getString("course"));
            userInfo.setDepartment(loginJSON.getString("department"));
            userInfo.setCoursePath(loginJSON.getString("coursePath"));
            userInfo.setCourseLength(loginJSON.getInt("courseLength"));
            userInfo.setRegistrationDate(loginJSON.getString("registrationDate"));

            HttpSession session = request.getSession(true);
            session.setAttribute("userInfo", userInfo);

            out.print("{\"result\": \"correct\"}");
        }
    } catch (UnirestException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unirest Exception");
    } catch (JSONException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "JSON Exception");
    } finally {
        out.close();
    }

}

From source file:com.mondospider.android.radar.SpiderSync.java

protected void theActualWork() {
    try {/*from  w  w w .j a v a2 s. c o  m*/
        Log.d(TAG, "Send http req for spider update - Wait Time (nextSyncIn) was: " + nextSyncIn);
        String responseString = LibHTTP.get(spiderLocationApiUrl);

        /*
         * String responseString = "{" + "\"latitude\":35.728926," +
         * "\"longitude\":139.71038," +
         * "\"datemodified\":\"Thu Mar 25 06:59:21 UTC 2010\"," + "}";
         */

        JSONObject jsonObj = new JSONObject(responseString);

        final double latitude = jsonObj.getDouble("latitude");
        final double longitude = jsonObj.getDouble("longitude");
        final String status = jsonObj.getString("status");
        int nextSyncIn2 = jsonObj.getInt("next_update_in");
        nextSyncIn = nextSyncIn2;
        fireUpdate(latitude, longitude, status);

    } catch (Exception ex) {
        ex.printStackTrace();
        // make sure that it waits a bit after an error
        nextSyncIn = 60;
    }
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

@Override
public @Nonnull Iterable<VirtualMachineProduct> listProducts(VirtualMachineProductFilterOptions options,
        Architecture architecture) throws InternalException, CloudException {
    Cache<VirtualMachineProduct> cache = Cache.getInstance(getProvider(), "VM.listProducts",
            VirtualMachineProduct.class, CacheLevel.REGION_ACCOUNT, TimePeriod.valueOf(1, "day"));
    final Iterable<VirtualMachineProduct> cachedProducts = cache.get(getContext());
    if (cachedProducts != null && cachedProducts.iterator().hasNext()) {
        return cachedProducts;
    }//from   ww w  .  ja v  a 2 s . c  o m
    JoyentMethod method = new JoyentMethod(provider);
    String json = method.doGetJson(provider.getEndpoint(), "packages");

    if (json == null) {
        return Collections.emptyList();
    }
    try {
        ArrayList<VirtualMachineProduct> products = new ArrayList<VirtualMachineProduct>();
        JSONArray list = new JSONArray(json);

        for (int i = 0; i < list.length(); i++) {
            JSONObject ob = list.getJSONObject(i);
            VirtualMachineProduct prd = new VirtualMachineProduct();

            if (ob.has("name")) {
                prd.setName(ob.getString("name"));
            }
            if (ob.has("memory")) {
                prd.setRamSize(new Storage<Megabyte>(ob.getInt("memory"), Storage.MEGABYTE));
            }
            if (ob.has("disk")) {
                prd.setRootVolumeSize(new Storage<Megabyte>(ob.getInt("disk"), Storage.MEGABYTE));
            }
            if (ob.has("vcpus")) {
                prd.setCpuCount(ob.getInt("vcpus"));
            }
            // SmartOS products are returned with 0 vCPUs as this metric doesn't apply
            // to them according to Joyent. In SmartOS you get some burstable capacity.
            // We will set them to 1 CPU anyway, as zero CPU is no CPU.
            if (prd.getCpuCount() == 0) {
                prd.setCpuCount(1);
            }
            if (ob.has("description")) {
                prd.setDescription(ob.getString("description"));
            } else {
                prd.setDescription(prd.getName());
            }
            prd.setProviderProductId(ob.getString("id"));
            if (options != null) {
                if (options.matches(prd))
                    products.add(prd);
            } else {
                products.add(prd);
            }
        }
        cache.put(getContext(), products);
        return products;
    } catch (JSONException e) {
        throw new CloudException(e);
    }
}

From source file:org.dasein.cloud.joyent.compute.Machine.java

private VirtualMachine toVirtualMachine(JSONObject ob) throws CloudException, InternalException {
    if (ob == null) {
        return null;
    }// w  w w  . j av  a  2s  .c o m
    try {
        VirtualMachine vm = new VirtualMachine();

        vm.setClonable(false);
        vm.setImagable(false);
        vm.setLastPauseTimestamp(-1L);
        vm.setPersistent(true);
        vm.setProviderDataCenterId(provider.getContext().getRegionId() + "a");
        vm.setProviderOwnerId(provider.getContext().getAccountNumber());
        vm.setProviderRegionId(provider.getContext().getRegionId());
        vm.setTerminationTimestamp(-1L);

        if (ob.has("id")) {
            vm.setProviderVirtualMachineId(ob.getString("id"));
        }
        if (ob.has("name")) {
            vm.setName(ob.getString("name"));
        }
        if (ob.has("ips")) {
            JSONArray ips = ob.getJSONArray("ips");
            ArrayList<String> pubIp = new ArrayList<String>();
            ArrayList<String> privIp = new ArrayList<String>();

            for (int i = 0; i < ips.length(); i++) {
                String addr = ips.getString(i);
                boolean pub = false;

                if (!addr.startsWith("10.") && !addr.startsWith("192.168.")) {
                    if (addr.startsWith("172.")) {
                        String[] nums = addr.split("\\.");

                        if (nums.length != 4) {
                            pub = true;
                        } else {
                            try {
                                int x = Integer.parseInt(nums[1]);

                                if (x < 16 || x > 31) {
                                    pub = true;
                                }
                            } catch (NumberFormatException ignore) {
                                // ignore
                            }
                        }
                    } else {
                        pub = true;
                    }
                }
                if (pub) {
                    pubIp.add(addr);
                } else {
                    privIp.add(addr);
                }
            }
            if (!pubIp.isEmpty()) {
                vm.setPublicIpAddresses(pubIp.toArray(new String[pubIp.size()]));
            }
            if (!privIp.isEmpty()) {
                vm.setPrivateIpAddresses(privIp.toArray(new String[privIp.size()]));
            }
        }
        if (ob.has("metadata")) {
            JSONObject md = ob.getJSONObject("metadata");
            JSONArray names = md.names();

            if (names != null) {
                for (int i = 0; i < names.length(); i++) {
                    String name = names.getString(i);

                    if (name.equals("dsnDescription")) {
                        vm.setDescription(md.getString(name));
                    } else if (name.equals("dsnTrueImage")) {
                        vm.setProviderMachineImageId(md.getString(name));
                    } else if (name.equals("dsnTrueProduct")) {
                        vm.setProductId(md.getString(name));
                    } else {
                        vm.addTag(name, md.getString(name));
                    }
                }
            }
        }
        if (vm.getProviderMachineImageId() == null && ob.has("dataset")) {
            vm.setProviderMachineImageId(getImageIdFromUrn(ob.getString("dataset")));
        }
        if (ob.has("created")) {
            vm.setCreationTimestamp(provider.parseTimestamp(ob.getString("created")));
        }
        vm.setPausable(false); // can't ever pause/resume joyent vms
        vm.setRebootable(false);
        if (ob.has("state")) {
            vm.setCurrentState(toState(ob.getString("state")));

            if (VmState.RUNNING.equals(vm.getCurrentState())) {
                vm.setRebootable(true);
            } else if (VmState.STOPPED.equals(vm.getCurrentState())) {
                vm.setImagable(true);
            }
        }
        vm.setLastBootTimestamp(vm.getCreationTimestamp());
        if (vm.getName() == null) {
            vm.setName(vm.getProviderVirtualMachineId());
        }
        if (vm.getDescription() == null) {
            vm.setDescription(vm.getName());
        }
        discover(vm);
        boolean isVMSmartOs = (vm.getPlatform().equals(Platform.SMARTOS));
        if (vm.getProductId() == null) {
            VirtualMachineProduct d = null;
            int disk, ram;

            disk = ob.getInt("disk");
            ram = ob.getInt("memory");
            for (VirtualMachineProduct prd : listProducts(vm.getArchitecture())) {
                d = prd;
                boolean isProductSmartOs = prd.getName().contains("smartos");
                if (prd.getRootVolumeSize().convertTo(Storage.MEGABYTE).intValue() == disk
                        && prd.getRamSize().intValue() == ram) {
                    if (isVMSmartOs && !isProductSmartOs) {
                        continue;
                    }
                    if (!isVMSmartOs && isProductSmartOs) {
                        continue;
                    }
                    vm.setProductId(prd.getProviderProductId());
                    break;
                }
            }
            if (vm.getProductId() == null) {
                vm.setProductId(d.getProviderProductId());
            }
        }
        return vm;
    } catch (JSONException e) {
        throw new CloudException(e);
    }
}

From source file:com.openerp.addons.note.AddFollowerFragment.java

public Boolean getPartnersFromServer() {

    boolean loaded = true;
    if (!flag) {//from  w  w  w .j  av  a  2  s .  c  om
        res_partners = new Res_PartnerDBHelper(scope.context());
        oe = res_partners.getOEInstance();
        try {
            ArrayList<Fields> cols = res_partners.getServerColumns();
            JSONObject fields = new JSONObject();
            for (Fields field : cols) {
                fields.accumulate("fields", field.getName());
            }
            JSONObject domain = new JSONObject();
            JSONArray ids = JSONDataHelper.intArrayToJSONArray(oe.getAllIds(res_partners));

            domain.accumulate("domain", new JSONArray("[[\"id\", \"not in\", " + ids.toString() + "]]"));

            JSONObject result = oe.search_read("res.partner", fields, domain, 0, 0, null, null);

            for (int i = 0; i < result.getInt("length"); i++) {
                JSONObject row = result.getJSONArray("records").getJSONObject(i);
                HashMap<String, Object> rowHash = new HashMap<String, Object>();
                @SuppressWarnings("unchecked")
                Iterator<String> keys = row.keys();

                while (keys.hasNext()) {
                    String key = keys.next();
                    rowHash.put(key, row.get(key));
                }
                final OEListViewRows listRow = new OEListViewRows(row.getInt("id"), rowHash);

                scope.context().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listRows.add(listRow);
                        listAdapters.refresh(listRows);
                    }
                });
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        loaded = false;
    }
    return loaded;
}

From source file:com.openerp.addons.note.AddFollowerFragment.java

public void addFollowers(int partnerId) {

    res_partners = new Res_PartnerDBHelper(scope.context());
    oe = res_partners.getOEInstance();/*from   w  w  w.j  a  va 2 s . c o m*/
    try {
        JSONObject args = new JSONObject();
        args.put("res_model", "note.note");
        args.put("res_id", record_id);
        args.put("message", message);
        JSONArray partner_ids = new JSONArray();
        partner_ids.put(6);
        partner_ids.put(false);
        JSONArray c_ids = new JSONArray();
        c_ids.put(partnerId);
        partner_ids.put(c_ids);
        args.put("partner_ids", new JSONArray("[" + partner_ids.toString() + "]"));
        JSONObject result = oe.createNew("mail.wizard.invite", args);
        int id = result.getInt("result");

        // calling mail.wizard.invite method
        JSONArray arguments = new JSONArray();
        JSONArray result_id = new JSONArray();
        result_id.put(id);
        arguments.put(result_id);

        JSONObject newValues = new JSONObject();
        newValues.put("default_res_model", "note.note");
        newValues.put("default_res_id", args.getInt("res_id"));
        JSONObject newContext = oe.updateContext(newValues);
        arguments.put(newContext);
        oe.call_kw("mail.wizard.invite", "add_followers", arguments);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.hp.mqm.atrf.octane.services.OctaneEntityService.java

private OctaneEntityCollection parseCollection(JSONObject jsonObj) {
    OctaneEntityCollection coll = new OctaneEntityCollection();

    int total = jsonObj.getInt("total_count");
    coll.setTotalCount(total);//from  w w  w . ja va2  s  .  c  om

    if (jsonObj.has("exceeds_total_count")) {
        boolean exceedsTotalCount = jsonObj.getBoolean("exceeds_total_count");
        coll.setExceedsTotalCount(exceedsTotalCount);
    }

    JSONArray entitiesJArr = jsonObj.getJSONArray("data");
    for (int i = 0; i < entitiesJArr.length(); i++) {

        JSONObject entObj = entitiesJArr.getJSONObject(i);
        OctaneEntity entity = parseEntity(entObj);

        coll.getData().add(entity);
    }

    return coll;
}