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.soomla.store.domain.virtualGoods.SingleUsePackVG.java

/** Constructor
 *
 * see parent/*from  w  ww  .  j a v a 2 s.c  o m*/
 */
public SingleUsePackVG(JSONObject jsonObject) throws JSONException {
    super(jsonObject);

    mGoodItemId = jsonObject.getString(JSONConsts.VGP_GOOD_ITEMID);
    mGoodAmount = jsonObject.getInt(JSONConsts.VGP_GOOD_AMOUNT);
}

From source file:com.skalski.raspberrycontrol.Activity_GPIO.java

Handler getClientHandler() {

    return new Handler() {
        @Override/*  w w w  .ja  v  a2 s .co m*/
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            JSONArray gpios;
            gpioArray = new ArrayList<Custom_GPIOAdapter>();
            gpioLayout.setRefreshing(false);

            Log.i(LOGTAG, LOGPREFIX + "new message received from server");

            try {

                root = new JSONObject(msg.obj.toString());

                if (root.has(TAG_ERROR)) {

                    String err = getResources().getString(R.string.com_msg_3) + root.getString(TAG_ERROR);
                    Log.e(LOGTAG, LOGPREFIX + root.getString(TAG_ERROR));
                    toast_connection_error(err);

                } else {

                    gpios = root.getJSONArray(TAG_GPIOSTATE);

                    for (int i = 0; i < gpios.length(); i++) {

                        JSONObject gpioss = gpios.getJSONObject(i);

                        int gpio = gpioss.getInt(TAG_GPIO);
                        int value = gpioss.getInt(TAG_VALUE);
                        String direction = gpioss.getString(TAG_DIRECTION);

                        gpioArray.add(new Custom_GPIOAdapter(gpio, value, direction));
                    }

                    if (gpios.length() == 0) {
                        Log.w(LOGTAG, LOGPREFIX + "can't find exported GPIO's on server side");
                        toast_connection_error(getResources().getString(R.string.error_msg_8));
                    }

                    if (gpioPinout.getDrawable().getConstantState() == getResources()
                            .getDrawable(R.drawable.gpio_unknown).getConstantState()) {
                        if (root.has(TAG_REVISION)) {
                            String revision;
                            revision = root.getString(TAG_REVISION);

                            Log.i(LOGTAG, LOGPREFIX + "set new GPIO layout image");

                            if (revision.equals("0002") || revision.equals("0003")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_1);

                            } else if (revision.equals("0004") || revision.equals("0005")
                                    || revision.equals("0006") || revision.equals("0007")
                                    || revision.equals("0008") || revision.equals("0009")
                                    || revision.equals("000d") || revision.equals("000e")
                                    || revision.equals("000f")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_2);

                            } else if (revision.equals("0010") || revision.equals("0011")) {

                                gpioPinout.setImageResource(R.drawable.gpio_pinout_3);

                            } else {
                                Log.wtf(LOGTAG, LOGPREFIX + "your Raspberry Pi board is weird");
                            }
                        }
                    }
                }

            } catch (Exception ex) {
                Log.e(LOGTAG, LOGPREFIX + "received invalid JSON object");
                toast_connection_error(getResources().getString(R.string.error_msg_2));
            }

            setListAdapter(new Custom_GPIOArrayAdapter(getApplicationContext(), gpioArray));
        }
    };
}

From source file:edu.txstate.dmlab.clusteringwiki.rest.TestController.java

/**
 * Save the details of the last executed step
 * @param executionId the execution id for the current test
 * @param model/* ww w .  j av  a 2s.c  o  m*/
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
@RequestMapping("/test/put/{executionId}")
public void saveStep(@PathVariable("executionId") String execId, HttpServletRequest request,
        HttpServletResponse response, Model model) throws Exception {

    String executionId = _cleanExtensions(execId);

    if (!isValidTest(request, executionId)) {
        sendOutput(response, "{\"error\":\"Invalid test execution id.\"}");
        return;
    }

    try {

        String data = null;
        InputStream is = request.getInputStream();

        if (is != null) {
            try {
                StringBuilder sb = new StringBuilder();
                String line;
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                data = sb.toString();
            } finally {
                is.close();
            }

        }

        if (data == null) {
            sendOutput(response, "{\"error\":\"No data received.\"}");
            return;
        }

        final JSONObject info = new JSONObject(data);

        final Integer stepId = info.getInt("stepId");
        final String cluster = info.getJSONObject("cluster").toString();
        final String times = info.getJSONObject("times").toString();
        final JSONObject tagExecutionInfo = info.getJSONObject("tagExecutionInfo");

        int itemCount = 0;
        final Iterator keys = tagExecutionInfo.keys();
        while (keys.hasNext()) {
            final String cnt = (String) keys.next();
            final Integer tagCount = Integer.valueOf(cnt);
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId,
                    tagCount);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            final JSONObject itemInfo = tagExecutionInfo.getJSONObject(cnt);

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(tagCount);
            exec.setBaseEffort(itemInfo.getDouble("baseEffort"));
            exec.setBaseRelevantEffort(itemInfo.getDouble("baseRelevantEffort"));
            exec.setUserEffort(itemInfo.getDouble("userEffort"));
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags(itemInfo.getJSONObject("tags").toString());

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
            itemCount++;
        }

        //if no tagged items
        if (itemCount == 0) {
            TestStepExecution exec = this.testStepExecutionDao.selectTestStepExecution(executionId, stepId, 0);

            if (exec != null) {
                sendOutput(response,
                        "{\"error\":\"This step has already been saved. Please contact an administrator.\"}");
                return;
            }

            exec = new TestStepExecution();
            exec.setExecutionId(executionId);
            exec.setTagCount(0);
            exec.setBaseEffort(0.0D);
            exec.setBaseRelevantEffort(0.0D);
            exec.setUserEffort(0.0D);
            exec.setCluster(cluster);
            exec.setTimes(times);
            exec.setStepId(stepId);
            exec.setTags("{}");

            if (this.isLoggedIn()) {
                exec.setUid(applicationUser.getUserId());
            }

            this.testStepExecutionDao.saveTestStepExecution(exec);
        }

        sendOutput(response, "{\"success\":true}");

    } catch (Exception e) {
        sendOutput(response, "{\"error\":" + JSONObject.quote(e.getMessage()) + "}");
        return;
    }

}

From source file:com.astifter.circatext.YahooJSONParser.java

private static int getInt(String tagName, JSONObject jObj) throws JSONException {
    return jObj.getInt(tagName);
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process get roles request//w  w  w  .j  a  v a 2s  .co m
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetRolesRequest(Channel channel, JSONObject requestObj) throws UserStoreException {
    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get roles.");
    }
    int limit = requestData.getInt(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_ROLE_LIMIT);

    if (limit == 0) {
        limit = CommonConstants.MAX_USER_LIST;
    }
    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();
    String[] roleNames = userStoreManager.doGetRoleNames("*", limit);
    JSONObject returnObject = new JSONObject();
    JSONArray usernameArray = new JSONArray(roleNames);
    returnObject.put("groups", usernameArray);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Roles retrieval completed.");
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            returnObject.toString());
}

From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java

/**
 * Process get roles request//from  ww  w  . ja  va  2 s . co m
 * @param channel netty channel
 * @param requestObj json request data object
 * @throws UserStoreException
 */
private void processGetUsersListRequest(Channel channel, JSONObject requestObj) throws UserStoreException {
    JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Starting to get users");
    }

    int limit = requestData.getInt(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_USER_LIMIT);
    String filter = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_USER_FILTER);

    if (limit == 0) {
        limit = CommonConstants.MAX_USER_LIST;
    }
    UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager();
    String[] roleNames = userStoreManager.doListUsers(filter, limit);
    JSONObject returnObject = new JSONObject();
    JSONArray usernameArray = new JSONArray(roleNames);
    returnObject.put("usernames", usernameArray);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Users list retrieval completed.");
    }
    writeResponse(channel,
            (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID),
            returnObject.toString());
}

From source file:com.nextgis.maplib.map.VectorLayer.java

public String createFromGeoJSON(JSONObject geoJSONObject) {
    try {//from  w  ww.j  a v  a 2  s  . c  o m
        //check crs
        boolean isWGS84 = true; //if no crs tag - WGS84 CRS
        if (geoJSONObject.has(GEOJSON_CRS)) {
            JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS);
            //the link is unsupported yet.
            if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) {
                return mContext.getString(R.string.error_crs_unsuported);
            }
            JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES);
            String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME);
            if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84
                isWGS84 = true;
            } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857") || crsName.equals("EPSG:3857")) { //Web Mercator
                isWGS84 = false;
            } else {
                return mContext.getString(R.string.error_crs_unsuported);
            }
        }

        //load contents to memory and reproject if needed
        JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES);
        if (0 == geoJSONFeatures.length()) {
            return mContext.getString(R.string.error_empty_dataset);
        }

        List<Feature> features = new ArrayList<>();
        List<Pair<String, Integer>> fields = new ArrayList<>();

        int geometryType = GTNone;
        for (int i = 0; i < geoJSONFeatures.length(); i++) {
            JSONObject jsonFeature = geoJSONFeatures.getJSONObject(i);
            //get geometry
            JSONObject jsonGeometry = jsonFeature.getJSONObject(GEOJSON_GEOMETRY);
            GeoGeometry geometry = GeoGeometry.fromJson(jsonGeometry);
            if (geometryType == GTNone) {
                geometryType = geometry.getType();
            } else if (!Geo.isGeometryTypeSame(geometryType, geometry.getType())) {
                //skip different geometry type
                continue;
            }

            //reproject if needed
            if (isWGS84) {
                geometry.setCRS(CRS_WGS84);
                geometry.project(CRS_WEB_MERCATOR);
            } else {
                geometry.setCRS(CRS_WEB_MERCATOR);
            }

            int nId = i;
            if (jsonFeature.has(GEOJSON_ID))
                nId = jsonFeature.getInt(GEOJSON_ID);
            Feature feature = new Feature(nId, fields); // ID == i
            feature.setGeometry(geometry);

            //normalize attributes
            JSONObject jsonAttributes = jsonFeature.getJSONObject(GEOJSON_PROPERTIES);
            Iterator<String> iter = jsonAttributes.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                Object value = jsonAttributes.get(key);
                int nType = NOT_FOUND;
                //check type
                if (value instanceof Integer || value instanceof Long) {
                    nType = FTInteger;
                } else if (value instanceof Double || value instanceof Float) {
                    nType = FTReal;
                } else if (value instanceof Date) {
                    nType = FTDateTime;
                } else if (value instanceof String) {
                    nType = FTString;
                } else if (value instanceof JSONObject) {
                    nType = NOT_FOUND;
                    //the some list - need to check it type FTIntegerList, FTRealList, FTStringList
                }

                if (nType != NOT_FOUND) {
                    int fieldIndex = NOT_FOUND;
                    for (int j = 0; j < fields.size(); j++) {
                        if (fields.get(j).first.equals(key)) {
                            fieldIndex = j;
                        }
                    }
                    if (fieldIndex == NOT_FOUND) { //add new field
                        Pair<String, Integer> fieldKey = Pair.create(key, nType);
                        fieldIndex = fields.size();
                        fields.add(fieldKey);
                    }
                    feature.setFieldValue(fieldIndex, value);
                }
            }
            features.add(feature);
        }

        String tableCreate = "CREATE TABLE IF NOT EXISTS " + mPath.getName() + " ( " + //table name is the same as the folder of the layer
                "_ID INTEGER PRIMARY KEY, " + "GEOM BLOB";
        for (int i = 0; i < fields.size(); ++i) {
            Pair<String, Integer> field = fields.get(i);

            tableCreate += ", " + field.first + " ";
            switch (field.second) {
            case FTString:
                tableCreate += "TEXT";
                break;
            case FTInteger:
                tableCreate += "INTEGER";
                break;
            case FTReal:
                tableCreate += "REAL";
                break;
            case FTDateTime:
                tableCreate += "TIMESTAMP";
                break;
            }
        }
        tableCreate += " );";

        GeoEnvelope extents = new GeoEnvelope();
        for (Feature feature : features) {
            //update bbox
            extents.merge(feature.getGeometry().getEnvelope());
        }

        //1. create table and populate with values
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(true);
        db.execSQL(tableCreate);
        for (Feature feature : features) {
            ContentValues values = new ContentValues();
            values.put("_ID", feature.getId());
            try {
                values.put("GEOM", feature.getGeometry().toBlob());
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fields.size(); ++i) {
                if (!feature.isValuePresent(i))
                    continue;
                switch (fields.get(i).second) {
                case FTString:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                case FTInteger:
                    values.put(fields.get(i).first, (int) feature.getFieldValue(i));
                    break;
                case FTReal:
                    values.put(fields.get(i).first, (double) feature.getFieldValue(i));
                    break;
                case FTDateTime:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                }
            }
            db.insert(mPath.getName(), "", values);
        }

        //2. save the layer properties to config.json
        mGeometryType = geometryType;
        mExtents = extents;
        mIsInitialized = true;
        setDefaultRenderer();

        save();

        //3. fill the geometry and labels array
        mVectorCacheItems = new ArrayList<>();
        for (Feature feature : features) {
            mVectorCacheItems.add(new VectorCacheItem(feature.getGeometry(), feature.getId()));
        }

        if (null != mParent) { //notify the load is over
            LayerGroup layerGroup = (LayerGroup) mParent;
            layerGroup.onLayerChanged(this);
        }

        return "";
    } catch (JSONException e) {
        e.printStackTrace();
        return e.getLocalizedMessage();
    }
}

From source file:com.nextgis.maplib.map.VectorLayer.java

@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mGeometryType = jsonObject.getInt(JSON_GEOMETRY_TYPE_KEY);
    mIsInitialized = jsonObject.getBoolean(JSON_IS_INITIALIZED_KEY);
    if (jsonObject.has(JSON_RENDERERPROPS_KEY)) {
        setDefaultRenderer();/*from  w w w. jav  a2 s .  com*/

        if (null != mRenderer && mRenderer instanceof IJSONStore) {
            IJSONStore jsonStore = (IJSONStore) mRenderer;
            jsonStore.fromJSON(jsonObject.getJSONObject(JSON_RENDERERPROPS_KEY));
        }
    }

    if (mIsInitialized) {
        mExtents = new GeoEnvelope();

        //load vector cache
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(false);
        String[] columns = new String[] { "_ID", "GEOM" };
        Cursor cursor = db.query(mPath.getName(), columns, null, null, null, null, null);
        if (null != cursor && cursor.moveToFirst()) {
            mVectorCacheItems = new ArrayList<>();
            do {
                try {
                    GeoGeometry geoGeometry = GeoGeometry.fromBlob(cursor.getBlob(1));
                    int nId = cursor.getInt(0);
                    mExtents.merge(geoGeometry.getEnvelope());
                    mVectorCacheItems.add(new VectorCacheItem(geoGeometry, nId));
                } catch (IOException | ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } while (cursor.moveToNext());
        }
    }
}

From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertWeatherData(String data, SQLiteDatabase db) {
    try {//w  w w . j  a v  a  2 s  .  com
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject array = jsonArray.getJSONObject(i);
            JSONObject jsonObject = array.getJSONObject("weather");

            long timestamp = jsonObject.getLong("timestamp");
            int year = jsonObject.getInt("year");
            int month = jsonObject.getInt("month");
            int day = jsonObject.getInt("day");
            int max_temp_c = jsonObject.getInt("max_temp_c");
            int max_temp_f = jsonObject.getInt("max_temp_f");
            int min_temp_c = jsonObject.getInt("min_temp_c");
            int min_temp_f = jsonObject.getInt("min_temp_f");
            int wind_speed_miles = jsonObject.getInt("wind_speed_miles");
            int wind_speed_km = jsonObject.getInt("wind_speed_km");
            String wind_direction = jsonObject.getString("wind_direction");
            int wind_degree = jsonObject.getInt("wind_degree");
            String icon_url = jsonObject.getString("icon_url");
            String description = jsonObject.getString("weather_description");
            Double precipitation = jsonObject.getDouble("precipitation");

            String inS = "INSERT INTO weather VALUES(" + timestamp + "," + year + "," + month + "," + day + ","
                    + max_temp_c + "," + max_temp_f + "," + min_temp_c + "," + min_temp_f + ","
                    + wind_speed_miles + "," + wind_speed_km + ",'" + wind_direction + "'," + wind_degree + ",'"
                    + icon_url + "','" + description + "'," + precipitation + ")";
            db.execSQL(inS);
        }
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
    return true;
}

From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertSurfData(String data, SQLiteDatabase db) {
    /* Delete any current versions with the same request timestamps */
    try {/*w  w  w.j av  a 2s  .co  m*/
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            db.execSQL("DELETE FROM surf WHERE timestamp = " + surf.getLong("timestamp"));
        }
    } catch (Exception e) {
        System.err.println("Could not delete data");
    }

    /* Now actually do the inserts! */
    try {
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            int location = surf.getInt("location");
            long timestamp = surf.getLong("timestamp");
            long localtime = surf.getLong("local_time");
            int year = surf.getInt("year");
            int month = surf.getInt("month");
            int day = surf.getInt("day");
            int hour = surf.getInt("hour");
            int minute = surf.getInt("minute");
            int faded_rating = surf.getInt("faded_rating");
            int solid_rating = surf.getInt("solid_rating");
            double min_surf = surf.getDouble("min_surf_height");
            double abs_min_surf = surf.getDouble("abs_min_surf_height");
            double max_surf = surf.getDouble("max_surf_height");
            double abs_max_surf = surf.getDouble("abs_max_surf_height");
            double swell_height = surf.getDouble("swell_height");
            double swell_period = surf.getDouble("swell_period");
            double swell_angle = surf.getDouble("swell_angle");
            String swell_direction = surf.getString("swell_direction");
            String swell_chart_url = surf.getString("swell_chart");
            String period_chart_url = surf.getString("period_chart");
            String wind_chart_url = surf.getString("wind_chart");
            String pressure_chart_url = surf.getString("pressure_chart");
            String sst_chart_url = surf.getString("sst_chart");

            String inS = "INSERT INTO surf VALUES(" + location + "," + timestamp + "," + localtime + "," + year
                    + "," + month + "," + day + "," + hour + "," + minute + "," + faded_rating + ","
                    + solid_rating + "," + min_surf + "," + abs_min_surf + "," + max_surf + "," + abs_max_surf
                    + "," + swell_height + "," + swell_period + "," + swell_angle + ",'" + swell_direction
                    + "','" + swell_chart_url + "','" + period_chart_url + "','" + wind_chart_url + "','"
                    + pressure_chart_url + "','" + sst_chart_url + "')";
            db.execSQL(inS);
        }
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
    return true;
}