Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.InviteToSharedAppFeedObj.java

public void handleDirectMessage(Context context, Contact from, JSONObject obj) {
    try {/*from w  w  w . j a va 2s .  c o  m*/
        String packageName = obj.getString(PACKAGE_NAME);
        String feedName = obj.getString("sharedFeedName");
        JSONArray ids = obj.getJSONArray(PARTICIPANTS);
        Intent launch = new Intent();
        launch.setAction(Intent.ACTION_MAIN);
        launch.addCategory(Intent.CATEGORY_LAUNCHER);
        launch.putExtra("type", "invite_app_feed");
        launch.putExtra("creator", false);
        launch.putExtra("sender", from.id);
        launch.putExtra("sharedFeedName", feedName);
        launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        long[] idArray = new long[ids.length()];
        for (int i = 0; i < ids.length(); i++) {
            idArray[i] = ids.getLong(i);
        }
        launch.putExtra("participants", idArray);
        launch.setPackage(packageName);
        final PackageManager mgr = context.getPackageManager();
        List<ResolveInfo> resolved = mgr.queryIntentActivities(launch, 0);
        if (resolved.size() == 0) {
            Toast.makeText(context, "Could not find application to handle invite.", Toast.LENGTH_SHORT).show();
            return;
        }
        ActivityInfo info = resolved.get(0).activityInfo;
        launch.setComponent(new ComponentName(info.packageName, info.name));
        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launch,
                PendingIntent.FLAG_CANCEL_CURRENT);

        (new PresenceAwareNotify(context)).notify("New Invitation from " + from.name,
                "Invitation received from " + from.name, "Click to launch application: " + packageName,
                contentIntent);
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage());
    }
}

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

Handler getClientHandler() {

    return new Handler() {
        @Override/*  ww w .  j  a v a 2  s  .  c o 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:uk.ac.imperial.presage2.core.cli.run.ExecutorModule.java

/**
 * <p>/*www .  ja v  a2s. com*/
 * Load an {@link AbstractModule} which can inject an
 * {@link ExecutorManager} with the appropriate {@link SimulationExecutor}s
 * as per provided configuration.
 * </p>
 * 
 * <p>
 * The executor config can be provided in two ways (in order of precedence):
 * </p>
 * <ul>
 * <li><code>executors.properties</code> file on the classpath. This file
 * should contain a <code>module</code> key who's value is the fully
 * qualified name of a class which extends {@link AbstractModule} and has a
 * public constructor which takes a single {@link Properties} object as an
 * argument or public no-args constructor. An instance of this class will be
 * returned.</li>
 * <li><code>executors.json</code> file on the classpath. This file contains
 * a specification of the executors to load in JSON format. If this file is
 * valid we will instantiate each executor defined in the spec and add it to
 * an {@link ExecutorModule} which will provide the bindings for them.</li>
 * </ul>
 * 
 * <h3>executors.json format</h3>
 * 
 * <p>
 * The <code>executors.json</code> file should contain a JSON object with
 * the following:
 * <ul>
 * <li><code>executors</code> key whose value is an array. Each element of
 * the array is a JSON object with the following keys:
 * <ul>
 * <li><code>class</code>: the fully qualified name of the executor class.</li>
 * <li><code>args</code>: an array of arguments to pass to a public
 * constructor of the class.</li>
 * <li><code>enableLogs</code> (optional): boolean value whether this
 * executor should save logs to file. Defaults to global value.</li>
 * <li><code>logDir</code> (optional): string path to save logs to. Defaults
 * to global value</li>
 * </ul>
 * </li>
 * <li><code>enableLogs</code> (optional): Global value for enableLogs for
 * each executor. Defaults to false.</li>
 * <li><code>logDir</code> (optional): Global value for logDir for each
 * executor. Default values depend on the executor.</li>
 * </ul>
 * </p>
 * <p>
 * e.g.:
 * </p>
 * 
 * <pre class="prettyprint">
 * {
 *    "executors": [{
 *       "class": "my.fully.qualified.Executor",
 *       "args": [1, "some string", true]
 *    },{
 *       ...
 *    }],
 * "enableLogs": true
 * }
 * </pre>
 * 
 * @return
 */
public static AbstractModule load() {
    Logger logger = Logger.getLogger(ExecutorModule.class);
    // look for executors.properties
    // This defines an AbstractModule to use instead of this one.
    // We try and load the module class given and return it.
    try {
        Properties execProps = new Properties();
        execProps.load(ExecutorModule.class.getClassLoader().getResourceAsStream("executors.properties"));
        String moduleName = execProps.getProperty("module", "");

        Class<? extends AbstractModule> module = Class.forName(moduleName).asSubclass(AbstractModule.class);
        // look for suitable ctor, either Properties parameter or default
        Constructor<? extends AbstractModule> ctor;
        try {
            ctor = module.getConstructor(Properties.class);
            return ctor.newInstance(execProps);
        } catch (NoSuchMethodException e) {
            ctor = module.getConstructor();
            return ctor.newInstance();
        }
    } catch (Exception e) {
        logger.debug("Could not create module from executors.properties");
    }
    // executors.properties fail, look for executors.json
    // This file defines a set of classes to load with parameters for the
    // constructor.
    // We try to create each defined executor and add it to this
    // ExecutorModule.
    try {
        // get executors.json file and parse to JSON.
        // throws NullPointerException if file doesn't exist, or
        // JSONException if we can't parse the JSON.
        InputStream is = ExecutorModule.class.getClassLoader().getResourceAsStream("executors.json");
        logger.debug("Processing executors from executors.json");
        JSONObject execConf = new JSONObject(new JSONTokener(new InputStreamReader(is)));
        // Create our module and look for executor specs under the executors
        // array in the JSON.
        ExecutorModule module = new ExecutorModule();
        JSONArray executors = execConf.getJSONArray("executors");

        // optional global settings
        boolean enableLogs = execConf.optBoolean("enableLogs", false);
        String logDir = execConf.optString("logDir");

        logger.info("Building Executors from executors.json");

        // Try and instantiate an instance of each executor in the spec.
        for (int i = 0; i < executors.length(); i++) {
            try {
                JSONObject executorSpec = executors.getJSONObject(i);
                String executorClass = executorSpec.getString("class");
                JSONArray args = executorSpec.getJSONArray("args");
                Class<? extends SimulationExecutor> clazz = Class.forName(executorClass)
                        .asSubclass(SimulationExecutor.class);
                // build constructor args.
                // We assume all types are in primitive form where
                // applicable.
                // The only available types are boolean, int, double and
                // String.
                Class<?>[] argTypes = new Class<?>[args.length()];
                Object[] argValues = new Object[args.length()];
                for (int j = 0; j < args.length(); j++) {
                    argValues[j] = args.get(j);
                    Class<?> type = argValues[j].getClass();
                    if (type == Boolean.class)
                        type = Boolean.TYPE;
                    else if (type == Integer.class)
                        type = Integer.TYPE;
                    else if (type == Double.class)
                        type = Double.TYPE;

                    argTypes[j] = type;
                }
                SimulationExecutor exe = clazz.getConstructor(argTypes).newInstance(argValues);
                logger.debug("Adding executor to pool: " + exe.toString());
                module.addExecutorInstance(exe);
                // logging config
                boolean exeEnableLog = executorSpec.optBoolean("enableLogs", enableLogs);
                String exeLogDir = executorSpec.optString("logDir", logDir);
                exe.enableLogs(exeEnableLog);
                if (exeLogDir.length() > 0) {
                    exe.setLogsDirectory(exeLogDir);
                }
            } catch (JSONException e) {
                logger.warn("Error parsing executor config", e);
            } catch (ClassNotFoundException e) {
                logger.warn("Unknown executor class in config", e);
            } catch (IllegalArgumentException e) {
                logger.warn("Illegal arguments for executor ctor", e);
            } catch (NoSuchMethodException e) {
                logger.warn("No matching public ctor for args in executor config", e);
            } catch (Exception e) {
                logger.warn("Could not create executor from specification", e);
            }
        }
        return module;
    } catch (JSONException e) {
        logger.debug("Could not create module from executors.json");
    } catch (NullPointerException e) {
        logger.debug("Could not open executors.json");
    }

    // no executor config, use a default config: 1 local sub process
    // executor.
    logger.info("Using default ExecutorModule.");
    return new ExecutorModule(1);
}

From source file:com.nonobay.fana.udacityandroidproject1popularmovies.FetchMovieTask.java

/**
 * Take the String representing the complete movies in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>/*w  w  w  .  ja v a 2s  .c  o  m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getMovieDataFromJson(String moviesJsonStr) throws JSONException {

    // Now we have a String representing the complete movie list in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    /* example
    {
    "page": 1,
    "results": [
        {
            "adult": false,
                "backdrop_path": "/razvUuLkF7CX4XsLyj02ksC0ayy.jpg",
                "genre_ids": [
            80,
                    28,
                    53
            ],
            "id": 260346,
                "original_language": "en",
                "original_title": "Taken 3",
                "overview": "Ex-government operative Bryan Mills finds his life is shattered when he's falsely accused of a murder that hits close to home. As he's pursued by a savvy police inspector, Mills employs his particular set of skills to track the real killer and exact his unique brand of justice.",
                "release_date": "2015-01-09",
                "poster_path": "/c2SSjUVYawDUnQ92bmTqsZsPEiB.jpg",
                "popularity": 11.737899,
                "title": "Taken 3",
                "video": false,
                "vote_average": 6.2,
                "vote_count": 698
        }
    ],
    "total_pages": 11543,
    "total_results": 230847
    }*/

    // These are the names of the JSON objects that need to be extracted.
    final String JSON_PAGE = "page";
    final String JSON_PAGE_TOTAL = "total_pages";
    final String JSON_MOVIE_LIST = "results";
    final String JSON_MOVIE_TOTAL = "total_results";

    final String JSON_MOVIE_ID = "id";
    final String JSON_MOVIE_TITLE = "original_title";
    final String JSON_MOVIE_DATE = "release_date";
    final String JSON_MOVIE_POSTER = "poster_path";
    final String JSON_MOVIE_OVERVIEW = "overview";
    final String JSON_MOVIE_VOTE_AVERAGE = "vote_average";

    try {

        JSONObject moviesJson = new JSONObject(moviesJsonStr);

        JSONArray movieArray = moviesJson.getJSONArray(JSON_MOVIE_LIST);

        // Insert the new movie information into the database
        Vector<ContentValues> cVVector = new Vector<>(movieArray.length());

        // These are the values that will be collected.
        String releaseTime;
        long movieId;
        double vote_average;
        String overview;
        String original_title;
        String poster_path;

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

            // Get the JSON object representing the movie
            JSONObject eachMovie = movieArray.getJSONObject(i);

            movieId = eachMovie.getLong(JSON_MOVIE_ID);
            original_title = eachMovie.getString(JSON_MOVIE_TITLE);
            overview = eachMovie.getString(JSON_MOVIE_OVERVIEW);
            poster_path = eachMovie.getString(JSON_MOVIE_POSTER);
            vote_average = eachMovie.getDouble(JSON_MOVIE_VOTE_AVERAGE);
            releaseTime = eachMovie.getString(JSON_MOVIE_DATE);

            ContentValues movieValues = new ContentValues();
            movieValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, movieId);
            movieValues.put(MovieContract.MovieEntry.COLUMN_ORIGINAL_TITLE, original_title);
            movieValues.put(MovieContract.MovieEntry.COLUMN_POSTER_THUMBNAIL, poster_path);
            movieValues.put(MovieContract.MovieEntry.COLUMN_SYNOPSIS, overview);
            movieValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, releaseTime);
            movieValues.put(MovieContract.MovieEntry.COLUMN_USER_RATING, vote_average);

            cVVector.add(movieValues);
        }

        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            mContext.getContentResolver().delete(MovieContract.MovieEntry.CONTENT_URI, null, null);
            mContext.getContentResolver().bulkInsert(MovieContract.MovieEntry.CONTENT_URI,
                    cVVector.toArray(new ContentValues[cVVector.size()]));
        }

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
}

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

public String createFromGeoJSON(JSONObject geoJSONObject) {
    try {/*from   w ww . jav a  2 s  .  co  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:org.loklak.api.iot.NOAAAlertServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;//from  w  w w .j  av  a 2s  . c  o  m
    }

    String content = new String(Files.readAllBytes(Paths.get(DAO.conf_dir + "/iot/scripts/counties.xml")));
    try {
        // Conversion of the XML Layers through PERL into the required JSON for well structured XML
        /*
        <resources>
        <string-array name="preference_county_entries_us">
            <item>Entire Country</item>
        </string-array>
        <string-array name="preference_county_entryvalues_us">
            <item>https://alerts.weather.gov/cap/us.php?x=0</item>
        </string-array>
        .
        .
        .
        Similarly every 2 DOM elements together in <resources> constitute a pair.
        </resources>
        */
        JSONObject json = XML.toJSONObject(content);
        PrintWriter sos = response.getWriter();
        JSONObject resourceObject = json.getJSONObject("resources");
        JSONArray stringArray = resourceObject.getJSONArray("string-array");
        JSONObject result = new JSONObject(true);

        // Extract and map the itemname and the url strings
        /*
        {
        "item": "Entire Country",
        "name": "preference_county_entries_us"
        },
        {
        "item": "https://alerts.weather.gov/cap/us.php?x=0",
        "name": "preference_county_entryvalues_us"
        }
        */
        for (int i = 0; i < stringArray.length(); i += 2) {
            JSONObject keyJSONObject = stringArray.getJSONObject(i);
            JSONObject valueJSONObject = stringArray.getJSONObject(i + 1);
            Object kItemObj = keyJSONObject.get("item");
            Object vItemObj = valueJSONObject.get("item");

            // Since instances are variable, we need to check if they're Arrays or Strings
            // The processing for the Key : Value mappings will change for each type of instance
            if (kItemObj instanceof JSONArray) {
                if (vItemObj instanceof JSONArray) {
                    JSONArray kArray = keyJSONObject.getJSONArray("item");
                    JSONArray vArray = valueJSONObject.getJSONArray("item");
                    for (int location = 0; location < kArray.length(); location++) {
                        String kValue = kArray.getString(location);
                        String vValue = vArray.getString(location);
                        result.put(kValue, vValue);
                    }
                }
            } else {
                // They are plain strings
                String kItemValue = keyJSONObject.getString("item");
                String vItemValue = valueJSONObject.getString("item");
                result.put(kItemValue, vItemValue);
            }

        }
        // Sample response in result has to be something like
        /*
        {
        "Entire Country": "https://alerts.weather.gov/cap/us.php?x=0",
        "Entire State": "https://alerts.weather.gov/cap/wy.php?x=0",
        "Autauga": "https://alerts.weather.gov/cap/wwaatmget.php?x=ALC001&y=0",
        "Baldwin": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC009&y=0",
        "Barbour": "https://alerts.weather.gov/cap/wwaatmget.php?x=WVC001&y=0",
        "Bibb": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC021&y=0",
        .
        .
        .
        And so on.
        }
        */

        sos.print(result.toString(2));
        sos.println();
    } catch (IOException e) {
        Log.getLog().warn(e);
        JSONObject json = new JSONObject(true);
        json.put("error", "Looks like there is an error in the conversion");
        json.put("type", "Error");
        PrintWriter sos = response.getWriter();
        sos.print(json.toString(2));
        sos.println();
    }

}

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

public Boolean insertAllData(String data) {
    JSONObject jsonArray = null;
    JSONArray weatherArray = null;/*from ww w  . j  a va2s.c  o  m*/
    JSONArray surfArray = null;

    try {
        jsonArray = new JSONObject(data);
        weatherArray = jsonArray.getJSONArray("weather");
        surfArray = jsonArray.getJSONArray("surf");
    } catch (Exception e) {
        System.err.println("couldn't parse JSON");
        return false;
    }

    SQLiteDatabase db = this.getWritableDatabase();
    int err_count = 0;

    /* Insert weather data */
    db.beginTransaction();
    Boolean weatherSuccess = insertWeatherData(weatherArray.toString(), db);
    if (!weatherSuccess) {
        err_count++;
        System.err.println("Error storing weather");
        db.endTransaction();
    } else {
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    /* Insert surf data - using transactions to help performance */
    db.beginTransaction();
    Boolean surfSuccess = insertSurfData(surfArray.toString(), db);
    if (!surfSuccess) {
        err_count++;
        System.err.println("Error storing surf");
        db.endTransaction();
    } else {
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    if (err_count > 0) {
        db.endTransaction();
        return false;
    }

    return true;
}

From source file:net.dv8tion.jda.core.handle.GuildMemberUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long id = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(id))
        return id;

    JSONObject userJson = content.getJSONObject("user");
    final long userId = userJson.getLong("id");
    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, userId, () -> {
            handle(responseNumber, allContent);
        });//from w  w  w.  j av  a  2 s. co m
        EventCache.LOG.debug("Got GuildMember update but JDA currently does not have the Guild cached. "
                + content.toString());
        return null;
    }

    MemberImpl member = (MemberImpl) guild.getMembersMap().get(userId);
    if (member == null) {
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> {
            handle(responseNumber, allContent);
        });
        EventCache.LOG.debug(
                "Got GuildMember update but Member is not currently present in Guild. " + content.toString());
        return null;
    }

    Set<Role> currentRoles = member.getRoleSet();
    List<Role> newRoles = toRolesList(guild, content.getJSONArray("roles"));

    //If newRoles is null that means that we didn't find a role that was in the array and was cached this event
    if (newRoles == null)
        return null;

    //Find the roles removed.
    List<Role> removedRoles = new LinkedList<>();
    each: for (Role role : currentRoles) {
        for (Iterator<Role> it = newRoles.iterator(); it.hasNext();) {
            Role r = it.next();
            if (role.equals(r)) {
                it.remove();
                continue each;
            }
        }
        removedRoles.add(role);
    }

    if (removedRoles.size() > 0)
        currentRoles.removeAll(removedRoles);
    if (newRoles.size() > 0)
        currentRoles.addAll(newRoles);

    if (removedRoles.size() > 0) {
        api.getEventManager()
                .handle(new GuildMemberRoleRemoveEvent(api, responseNumber, guild, member, removedRoles));
    }
    if (newRoles.size() > 0) {
        api.getEventManager().handle(new GuildMemberRoleAddEvent(api, responseNumber, guild, member, newRoles));
    }
    if (content.has("nick")) {
        String prevNick = member.getNickname();
        String newNick = content.isNull("nick") ? null : content.getString("nick");
        if (!Objects.equals(prevNick, newNick)) {
            member.setNickname(newNick);
            api.getEventManager().handle(
                    new GuildMemberNickChangeEvent(api, responseNumber, guild, member, prevNick, newNick));
        }
    }
    return null;
}

From source file:org.eclipse.orion.internal.server.servlets.file.FileHandlerV1.java

private void handlePatchContents(HttpServletRequest request, BufferedReader requestReader,
        HttpServletResponse response, IFileStore file)
        throws IOException, CoreException, NoSuchAlgorithmException, JSONException, ServletException {
    JSONObject changes = OrionServlet.readJSONRequest(request);
    //read file to memory
    Reader fileReader = new InputStreamReader(file.openInputStream(EFS.NONE, null));
    StringWriter oldFile = new StringWriter();
    IOUtilities.pipe(fileReader, oldFile, true, false);
    StringBuffer oldContents = oldFile.getBuffer();

    JSONArray changeList = changes.getJSONArray("diff");
    for (int i = 0; i < changeList.length(); i++) {
        JSONObject change = changeList.getJSONObject(i);
        long start = change.getLong("start");
        long end = change.getLong("end");
        String text = change.getString("text");
        oldContents.replace((int) start, (int) end, text);
    }/*from www.  j  av  a 2s  .  c  o  m*/

    String newContents = oldContents.toString();
    boolean failed = false;
    if (changes.has("contents")) {
        String contents = changes.getString("contents");
        if (!newContents.equals(contents)) {
            failed = true;
            newContents = contents;
        }
    }
    Writer fileWriter = new OutputStreamWriter(file.openOutputStream(EFS.NONE, null), "UTF-8");
    IOUtilities.pipe(new StringReader(newContents), fileWriter, false, true);
    if (failed) {
        statusHandler.handleRequest(request, response,
                new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_NOT_ACCEPTABLE,
                        "Bad File Diffs. Please paste this content in a bug report: \u00A0\u00A0    "
                                + changes.toString(),
                        null));
        return;
    }

    // return metadata with the new Etag
    handleGetMetadata(request, response, response.getWriter(), file);
}

From source file:net.portalblockz.portalbot.serverdata.JSONConfigManager.java

public void serializeRepos() {
    JSONArray repoArray = configObject.optJSONArray("git-repos");
    if (repoArray != null) {
        for (int i = 0; i < repoArray.length(); i++) {
            JSONObject repoData = repoArray.optJSONObject(i);
            if (repoData != null) {
                String name = repoData.getString("name");
                String dispName = repoData.optString("dispName");
                dispName = (dispName == null || dispName.length() < 1) ? name : dispName;
                List<String> repoChannels = new ArrayList<>();
                for (int n = 0; n < repoData.getJSONArray("channels").length(); n++) {
                    repoChannels.add(repoData.getJSONArray("channels").getString(n).toLowerCase());
                }/*from www.jav  a 2  s.c o  m*/
                repoMap.put(name.toLowerCase(), repoChannels);
                repoDispNames.put(name.toLowerCase(), dispName);
            }
        }
    }
}