Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

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

Prototype

public int optInt(String key, int defaultValue) 

Source Link

Document

Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number.

Usage

From source file:com.androidquery.simplefeed.fragments.FeedFragment.java

public void notiCb(String url, JSONObject jo, AjaxStatus status) {

    AQUtility.debug("noti", jo);

    if (jo != null) {

        int count = 0;

        PQuery aq = aq2.recycle(header);

        /*/*from   w w  w  . j  ava 2s. c o  m*/
        JSONObject sum = jo.optJSONObject("summary");
                
        if(sum != null){
           count = sum.optInt("unseen_count", 0);                    
        }*/

        JSONArray ja = jo.optJSONArray("data");
        for (int i = 0; i < ja.length(); i++) {
            JSONObject noti = ja.optJSONObject(i);
            if (noti.optInt("unread", 0) != 0) {
                count++;
            }
        }

        String message = count + " " + getString(R.string.n_notifications);
        aq.id(R.id.text_noti).text(message);
        int colorId = R.color.noti;
        int tf = Typeface.BOLD;
        if (count == 0) {
            colorId = R.color.grey;
            tf = Typeface.NORMAL;
        }

        aq.textColor(getResources().getColor(colorId)).getTextView().setTypeface(null, tf);

    }

}

From source file:org.andstatus.app.backup.MyBackupDescriptor.java

static MyBackupDescriptor fromOldParcelFileDescriptor(ParcelFileDescriptor parcelFileDescriptor,
        ProgressLogger progressLogger) {
    MyBackupDescriptor myBackupDescriptor = new MyBackupDescriptor(progressLogger);
    if (parcelFileDescriptor != null) {
        myBackupDescriptor.fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        JSONObject jso = FileDescriptorUtils.getJSONObject(parcelFileDescriptor.getFileDescriptor());
        myBackupDescriptor.backupSchemaVersion = jso.optInt(KEY_BACKUP_SCHEMA_VERSION,
                myBackupDescriptor.backupSchemaVersion);
        myBackupDescriptor.createdDate = jso.optLong(KEY_CREATED_DATE, myBackupDescriptor.createdDate);
        myBackupDescriptor.applicationVersionCode = jso.optInt(KEY_APPLICATION_VERSION_CODE,
                myBackupDescriptor.applicationVersionCode);
        myBackupDescriptor.accountsCount = jso.optLong(KEY_ACCOUNTS_COUNT, myBackupDescriptor.accountsCount);
        if (myBackupDescriptor.backupSchemaVersion != BACKUP_SCHEMA_VERSION) {
            try {
                MyLog.w(TAG, "Bad backup descriptor: " + jso.toString(2));
            } catch (JSONException e) {
                MyLog.d(TAG, "Bad backup descriptor: " + jso.toString(), e);
            }/*ww  w. j  a  v  a  2 s .co m*/
        }
    }
    return myBackupDescriptor;
}

From source file:com.rapid.actions.Webservice.java

@Override
public JSONObject doAction(RapidRequest rapidRequest, JSONObject jsonAction) throws Exception {

    _logger.trace("Webservice action : " + jsonAction);

    // get the application
    Application application = rapidRequest.getApplication();

    // get the page
    Page page = rapidRequest.getPage();/*from  w ww.  j  a v a 2s  .com*/

    // get the webservice action call sequence
    int sequence = jsonAction.optInt("sequence", 1);

    // placeholder for the object we're about to return
    JSONObject jsonData = null;

    // only proceed if there is a request and application and page
    if (_request != null && application != null && page != null) {

        // get any json inputs 
        JSONArray jsonInputs = jsonAction.optJSONArray("inputs");

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Webservice action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), jsonInputs.toString());

        }

        // if there is either no cache or we got no data
        if (jsonData == null) {

            // get the body into a string
            String body = _request.getBody().trim();
            // remove prolog if present
            if (body.indexOf("\"?>") > 0)
                body = body.substring(body.indexOf("\"?>") + 3).trim();
            // check number of parameters
            int pCount = Strings.occurrences(body, "?");
            // throw error if incorrect
            if (pCount != jsonInputs.length())
                throw new Exception("Request has " + pCount + " parameter" + (pCount == 1 ? "" : "s") + ", "
                        + jsonInputs.length() + " provided");
            // retain the current position
            int pos = body.indexOf("?");
            // keep track of the index of the ?
            int index = 0;
            // if there are any question marks
            if (pos > 0 && jsonInputs.length() > index) {
                // loop, but check condition at the end
                do {
                    // get the input
                    JSONObject input = jsonInputs.getJSONObject(index);
                    // url escape the value
                    String value = XML.escape(input.optString("value"));
                    // replace the ? with the input value
                    body = body.substring(0, pos) + value + body.substring(pos + 1);
                    // look for the next question mark
                    pos = body.indexOf("?", pos + 1);
                    // inc the index for the next round
                    index++;
                    // stop looping if no more ?
                } while (pos > 0);
            }

            // retrieve the action
            String action = _request.getAction();
            // create a placeholder for the request url
            URL url = null;
            // get the request url
            String requestURL = _request.getUrl();

            // if we got one
            if (requestURL != null) {

                // if the given request url starts with http use it as is, otherwise use the soa servlet
                if (_request.getUrl().startsWith("http")) {
                    // trim it
                    requestURL = requestURL.trim();
                    // insert any parameters
                    requestURL = application
                            .insertParameters(rapidRequest.getRapidServlet().getServletContext(), requestURL);
                    // use the url 
                    url = new URL(requestURL);
                } else {
                    // get our request
                    HttpServletRequest httpRequest = rapidRequest.getRequest();
                    // make a url for the soa servlet
                    url = new URL(httpRequest.getScheme(), httpRequest.getServerName(),
                            httpRequest.getServerPort(), httpRequest.getContextPath() + "/soa");
                    // check whether we have any id / version seperators
                    String[] actionParts = action.split("/");
                    // add this app and version if none
                    if (actionParts.length < 2)
                        action = application.getId() + "/" + application.getVersion() + "/" + action;
                }

                // establish the connection
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                // if we are requesting from ourself
                if (url.getPath().startsWith(rapidRequest.getRequest().getContextPath())) {
                    // get our session id
                    String sessionId = rapidRequest.getRequest().getSession().getId();
                    // add it to the call for internal authentication
                    connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionId);
                }

                // set the content type and action header accordingly
                if ("SOAP".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    connection.setRequestProperty("SOAPAction", action);
                } else if ("JSON".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "application/json");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                } else if ("XML".equals(_request.getType())) {
                    connection.setRequestProperty("Content-Type", "text/xml");
                    if (action.length() > 0)
                        connection.setRequestProperty("Action", action);
                }

                // if a body has been specified
                if (body.length() > 0) {

                    // Triggers POST.
                    connection.setDoOutput(true);

                    // get the output stream from the connection into which we write the request
                    OutputStream output = connection.getOutputStream();

                    // write the processed body string into the request output stream
                    output.write(body.getBytes("UTF8"));
                }

                // check the response code
                int responseCode = connection.getResponseCode();

                // read input stream if all ok, otherwise something meaningful should be in error stream
                if (responseCode == 200) {

                    // get the input stream
                    InputStream response = connection.getInputStream();
                    // prepare an soaData object
                    SOAData soaData = null;

                    // read the response accordingly
                    if ("JSON".equals(_request.getType())) {
                        SOAJSONReader jsonReader = new SOAJSONReader();
                        String jsonResponse = Strings.getString(response);
                        soaData = jsonReader.read(jsonResponse);
                    } else {
                        SOAXMLReader xmlReader = new SOAXMLReader(_request.getRoot());
                        soaData = xmlReader.read(response);
                    }

                    SOADataWriter jsonWriter = new SOARapidWriter(soaData);

                    String jsonString = jsonWriter.write();

                    jsonData = new JSONObject(jsonString);

                    if (actionCache != null)
                        actionCache.put(application.getId(), getId(), jsonInputs.toString(), jsonData);

                    response.close();

                } else {

                    InputStream response = connection.getErrorStream();

                    String errorMessage = null;

                    if ("SOAP".equals(_request.getType())) {

                        String responseXML = Strings.getString(response);

                        errorMessage = XML.getElementValue(responseXML, "faultcode");

                    }

                    if (errorMessage == null) {

                        BufferedReader rd = new BufferedReader(new InputStreamReader(response));

                        errorMessage = rd.readLine();

                        rd.close();

                    }

                    // log the error
                    _logger.error(errorMessage);

                    // only if there is no application cache show the error, otherwise it sends an empty response
                    if (actionCache == null) {

                        throw new JSONException(
                                " response code " + responseCode + " from server : " + errorMessage);

                    } else {

                        _logger.debug("Error not shown to user due to cache : " + errorMessage);

                    }

                }

                connection.disconnect();

            } // request url != null

        } // jsonData == null

    } // got app and page

    // if the jsonData is still null make an empty one
    if (jsonData == null)
        jsonData = new JSONObject();

    // add the sequence
    jsonData.put("sequence", sequence);

    // return the object
    return jsonData;

}

From source file:net.geco.model.iojson.PersistentStore.java

public void importCourses(JSONStore store, Registry registry, Factory factory) throws JSONException {
    JSONArray courses = store.getJSONArray(K.COURSES);
    for (int i = 0; i < courses.length(); i++) {
        JSONObject c = courses.getJSONObject(i);
        Course course = store.register(factory.createCourse(), c.getInt(K.ID));
        course.setName(c.getString(K.NAME));
        course.setLength(c.getInt(K.LENGTH));
        course.setClimb(c.getInt(K.CLIMB));
        course.setMassStartTime(new Date(c.optLong(K.START, TimeManager.NO_TIME_l))); // MIGR v2.x -> v2.2
        course.setCourseSet(store.retrieve(c.optInt(K.COURSESET, 0), CourseSet.class));
        JSONArray codez = c.getJSONArray(K.CODES);
        int[] codes = new int[codez.length()];
        for (int j = 0; j < codes.length; j++) {
            codes[j] = codez.getInt(j);//  w w w .  ja  v a  2  s  .c o m
        }
        course.setCodes(codes);
        if (c.has(K.SECTIONS)) {
            JSONArray sectionz = c.getJSONArray(K.SECTIONS);
            for (int j = 0; j < sectionz.length(); j++) {
                JSONObject sectionTuple = sectionz.getJSONObject(j);
                Section section = store.register(factory.createSection(), sectionTuple.getInt(K.ID));
                section.setStartIndex(sectionTuple.getInt(K.START_ID));
                section.setName(sectionTuple.getString(K.NAME));
                section.setType(SectionType.valueOf(sectionTuple.getString(K.TYPE)));
                section.setNeutralized(sectionTuple.optBoolean(K.NEUTRALIZED, false));
                course.putSection(section);
            }
            course.refreshSectionCodes();
        }
        registry.addCourse(course);
    }
    registry.ensureAutoCourse(factory);
}

From source file:net.geco.model.iojson.PersistentStore.java

public void importCategories(JSONStore store, Registry registry, Factory factory) throws JSONException {
    JSONArray categories = store.getJSONArray(K.CATEGORIES);
    for (int i = 0; i < categories.length(); i++) {
        JSONObject c = categories.getJSONObject(i);
        Category category = store.register(factory.createCategory(), c.getInt(K.ID));
        category.setName(c.getString(K.NAME));
        category.setLongname(c.getString(K.LONG));
        category.setCourse(store.retrieve(c.optInt(K.COURSE, 0), Course.class));
        category.setCourseSet(store.retrieve(c.optInt(K.COURSESET, 0), CourseSet.class));
        registry.addCategory(category);// www. j  av  a2 s.c o  m
    }
}

From source file:com.tapfortap.phonegap.TapForTapPhoneGapPlugin.java

private LayoutParams getLayoutParamsForOptions(JSONObject options) {
    int widthPx = options.optInt("width", LayoutParams.MATCH_PARENT);
    int heightPx = options.optInt("height", 50);
    float widthDip;
    if (widthPx > 0) {
        widthDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, widthPx,
                cordova.getActivity().getResources().getDisplayMetrics());
    } else {/*from   ww  w. j a  va2 s  .c om*/
        widthDip = widthPx;
    }
    float heightDip = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, heightPx,
            cordova.getActivity().getResources().getDisplayMetrics());
    return new LayoutParams((int) widthDip, (int) heightDip);
}

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

static final Quilt createFromJSONObject(JSONObject jsonObject) throws JSONException {

    int rowCount = jsonObject.optInt("rowCount", 0);
    int columnCount = jsonObject.optInt("columnCount", 0);
    float width = (float) jsonObject.optDouble("width", 0);
    float height = (float) jsonObject.optDouble("height", 0);

    Quilt quilt = new Quilt(rowCount, columnCount, width, height);

    if (jsonObject.has("quiltBlocks")) {
        JSONArray jsonQuiltBlocks = jsonObject.getJSONArray("quiltBlocks");

        int index = -1;
        for (int row = 0; row < quilt.m_rowCount; ++row) {
            for (int column = 0; column < quilt.m_columnCount; ++column) {
                index += 1;/*from   w ww. j  a v  a2 s  .c  o  m*/
                if (index < jsonQuiltBlocks.length()) {
                    JSONObject jsonQuiltBlock = jsonQuiltBlocks.optJSONObject(index);
                    if (jsonQuiltBlock != null) {
                        QuiltBlock quiltBlock = QuiltBlock.createFromJSONObject(jsonQuiltBlock);
                        quilt.setQuiltBlock(row, column, quiltBlock);
                    }
                }
            }
        }
    }

    quilt.m_new = false;
    return quilt;
}

From source file:com.marianhello.cordova.bgloc.Config.java

public static Config fromJSONArray(JSONArray data) throws JSONException {
    JSONObject jObject = data.getJSONObject(0);
    Config config = new Config();
    config.setStationaryRadius((float) jObject.optDouble("stationaryRadius", config.getStationaryRadius()));
    config.setDistanceFilter(jObject.optInt("distanceFilter", config.getDistanceFilter()));
    config.setDesiredAccuracy(jObject.optInt("desiredAccuracy", config.getDesiredAccuracy()));
    config.setDebugging(jObject.optBoolean("debug", config.isDebugging()));
    config.setNotificationTitle(jObject.optString("notificationTitle", config.getNotificationTitle()));
    config.setNotificationText(jObject.optString("notificationText", config.getNotificationText()));
    config.setStopOnTerminate(jObject.optBoolean("stopOnTerminate", config.getStopOnTerminate()));
    config.setStartOnBoot(jObject.optBoolean("startOnBoot", config.getStartOnBoot()));
    config.setServiceProvider(jObject.optInt("locationService", config.getServiceProvider().asInt()));
    config.setInterval(jObject.optInt("interval", config.getInterval()));
    config.setFastestInterval(jObject.optInt("fastestInterval", config.getFastestInterval()));
    config.setActivitiesInterval(jObject.optInt("activitiesInterval", config.getActivitiesInterval()));
    config.setNotificationIconColor(//from   ww  w. j  a v a 2 s .  c  o  m
            jObject.optString("notificationIconColor", config.getNotificationIconColor()));
    config.setLargeNotificationIcon(
            jObject.optString("notificationIconLarge", config.getLargeNotificationIcon()));
    config.setSmallNotificationIcon(
            jObject.optString("notificationIconSmall", config.getSmallNotificationIcon()));
    config.setStartForeground(jObject.optBoolean("startForeground", config.getStartForeground()));
    config.setUrl(jObject.optString("url", config.getUrl()));
    config.setMethod(jObject.optString("method", config.getMethod()));
    config.setHeaders(jObject.optJSONObject("headers"));
    config.setParams(jObject.optJSONObject("params"));
    return config;
}

From source file:com.sina.weibo.sdk_lib.openapi.models.Visible.java

public static Visible parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//from  w ww  .  ja  va2  s .co m

    Visible visible = new Visible();
    visible.type = jsonObject.optInt("type", 0);
    visible.list_id = jsonObject.optInt("list_id", 0);

    return visible;
}

From source file:com.google.blockly.model.FieldImage.java

public static FieldImage fromJson(JSONObject json) {
    return new FieldImage(json.optString("name"),
            json.optString("src", "https://www.gstatic.com/codesite/ph/images/star_on.gif"),
            json.optInt("width", 15), json.optInt("height", 15), json.optString("alt", "*"));
}