Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:conroller.UserController.java

private static ArrayList<UserModel> getJSONData(String response) throws IOException, JSONException {
    String userName, fullName, email, address, gender, telNo, password, typeOfUser;
    ArrayList<UserModel> arrayList = new ArrayList<>();
    final JSONObject jSONObject = new JSONObject(response);
    final JSONArray array = jSONObject.getJSONArray("server_response");
    for (int i = 0; i < array.length(); i++) {
        final JSONObject details = array.getJSONObject(i);
        try {//from w  ww . j ava  2 s  . c  om
            userName = String.valueOf(details.getString("userName"));
        } catch (Exception ex) {
            userName = null;
        }
        try {
            fullName = String.valueOf(details.getString("fullName"));
        } catch (Exception e) {
            fullName = null;
        }
        try {
            email = String.valueOf(details.getString("email"));
        } catch (Exception e) {
            email = null;
        }
        try {
            address = String.valueOf(details.getString("address"));
        } catch (Exception e) {
            address = null;
        }
        try {
            gender = String.valueOf(details.getString("gender"));
        } catch (Exception e) {
            gender = null;
        }
        try {
            telNo = String.valueOf(details.getString("telNo"));
        } catch (Exception e) {
            telNo = null;
        }
        try {
            password = String.valueOf(details.getString("password"));
        } catch (Exception e) {
            password = null;
        }
        try {
            typeOfUser = String.valueOf(details.getString("typeOfUser"));
        } catch (Exception e) {
            typeOfUser = null;
        }
        UserModel model = new UserModel(userName, fullName, email, address, gender, telNo, password,
                typeOfUser);
        arrayList.add(model);
    }
    return arrayList;
}

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

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods./*ww w.  ja va  2 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();

    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        JSONObject recordBook = new APIConsumer().consume("getRecordBook", username, password);
        JSONObject result = new JSONObject();
        result.put("average", recordBook.getDouble("average"));
        result.put("weightedAverage", recordBook.getDouble("weightedAverage"));

        JSONArray exams = recordBook.getJSONArray("exams");
        float acquiredCFU = 0;
        int totalExams = 0;
        for (int i = 0; i < exams.length(); i++) {
            if (!exams.getJSONObject(i).getString("vote").contains("/")) {
                acquiredCFU += exams.getJSONObject(i).getInt("cfu");
                totalExams++;
            }
        }
        double percentCfuUgly = (acquiredCFU * 100) / userInfo.getTotalCFU();
        //Arrotonda la percentuale alla prima cifra decimale
        double percentCfu = Math.round(percentCfuUgly * 10D) / 10D;
        result.put("totalCFU", (int) userInfo.getTotalCFU());
        result.put("acquiredCFU", (int) acquiredCFU);
        result.put("percentCFU", percentCfu);
        result.put("totalExams", totalExams);

        out.write(result.toString());
    } catch (UnirestException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } catch (JSONException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } finally {
        out.close();
    }

}

From source file:nl.hnogames.domoticzapi.Parsers.StatusInfoParser.java

@Override
public void parseResult(String result) {
    // Change the result data here so the view class gets the ready data

    try {//from  www. ja va2 s  .  c  o m

        JSONArray jsonArray = new JSONArray(result);
        JSONObject jsonObject = jsonArray.getJSONObject(0);

        statusReceiver.onReceiveStatus(new ExtendedStatusInfo(jsonObject));

    } catch (JSONException error) {
        Log.d(TAG, "StatusInfoParser onError");
        statusReceiver.onError(error);
    }
}

From source file:org.wso2.carbon.dataservices.core.description.query.MongoQuery.java

private String getElementValueFromJson(String jsonString, JSONObject object, String jsonPath)
        throws JSONException {
    String value = null;/*  w w w.jav  a2s . c  o  m*/
    JSONObject tempObject = object;
    JSONArray tempArray;
    String[] tokens = jsonPath.split("\\.");
    if (tokens[0].equals(DBConstants.MongoDB.RESULT_COLUMN_NAME.toLowerCase())) {
        if (tokens.length == 1) {
            value = jsonString;
        } else {
            for (int i = 1; i < tokens.length; i++) {
                if (i == tokens.length - 1) {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        value = tempArray.getString((Integer) arrayObjects[1]);
                    } else {
                        value = tempObject.getString(tokens[i]);
                    }
                } else {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        tempObject = tempArray.getJSONObject((Integer) arrayObjects[1]);
                    } else {
                        tempObject = tempObject.getJSONObject(tokens[i]);
                    }
                }
            }
        }
        return value;
    } else {
        return null;
    }
}

From source file:com.timrae.rikaidroid.MainActivity.java

private void addKuromojiWebItems(StringBuilder builder, JSONArray tokens) {
    for (int i = 0; i < tokens.length(); i++) {
        String reading;//w  w  w.ja v  a  2s  .  c o m
        String surface;
        try {
            JSONObject token = tokens.getJSONObject(i);
            //base = token.getString("base");
            reading = token.getString("reading");
            surface = token.getString("surface");

            String formattedText;
            if (hasKanji(surface)) {
                // Try to join the surface form with any particles following it
                if (i < tokens.length() - 1) {
                    JSONObject nextToken = tokens.getJSONObject(i);
                    String pos = nextToken.getString("pos");
                    if (pos.contains("") || pos.contains("")) {
                        surface += nextToken.getString("surface");
                        i++;
                    }
                }
                formattedText = makeFurigana(surface, katToHira(reading));
                if (isAedictPresent(this)) {
                    formattedText = String.format(INTENT_URL, token.getString("base"), formattedText);
                }
            } else {
                formattedText = surface;
            }

            builder.append(formattedText);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

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

Handler getClientHandler() {

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

/**
 * <p>/*from www  . j  av  a 2s .  c o m*/
 * 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/>// ww  w .j a  v a2s. 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 ww w  .  j  a  va2 s .c  om
        //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;//w w w .  j av a2  s.com
    }

    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();
    }

}