Example usage for org.json JSONTokener JSONTokener

List of usage examples for org.json JSONTokener JSONTokener

Introduction

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

Prototype

public JSONTokener(String s) 

Source Link

Document

Construct a JSONTokener from a string.

Usage

From source file:uk.ac.imperial.presage2.web.SimulationsTreeServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    logRequest(req);/*from  w  w  w .j  a  v  a 2 s  . c  om*/
    String path = req.getPathInfo();
    Matcher matcher = ID_REGEX.matcher(path);
    if (matcher.matches()) {
        long simId = Integer.parseInt(matcher.group(1));
        try {
            // get data sent to us
            JSONObject input = new JSONObject(new JSONTokener(req.getReader()));
            if (simId > 0 && (input.getString("parentId").equalsIgnoreCase("root")
                    || input.getLong("parentId") > 0)) {
                PersistentSimulation sim = sto.getSimulationById(simId);
                PersistentSimulation parent = null;
                if (input.getString("parentId").equalsIgnoreCase("root")) {
                    parent = null;
                } else if (input.getLong("parentId") > 0 && input.getLong("parentId") != simId) {
                    parent = sto.getSimulationById(input.getLong("parentId"));
                } else {
                    resp.setStatus(400);
                    return;
                }
                if (sim != null) {
                    sim.setParentSimulation(parent);
                    resp.setStatus(200);
                    return;
                }
            }
            resp.setStatus(400);
        } catch (JSONException e) {
            resp.setStatus(400);
        }
    } else {
        resp.setStatus(400);
    }
}

From source file:com.wb.launcher3.InstallShortcutReceiver.java

public static void removeFromInstallQueue(SharedPreferences sharedPrefs, ArrayList<String> packageNames) {
    synchronized (sLock) {
        Set<String> strings = sharedPrefs.getStringSet(APPS_PENDING_INSTALL, null);
        if (DBG) {
            Log.d(TAG, "APPS_PENDING_INSTALL: " + strings + ", removing packages: " + packageNames);
        }/*w  w w.j a va 2 s  . c o m*/
        if (strings != null) {
            Set<String> newStrings = new HashSet<String>(strings);
            Iterator<String> newStringsIter = newStrings.iterator();
            while (newStringsIter.hasNext()) {
                String json = newStringsIter.next();
                try {
                    JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
                    Intent launchIntent = Intent.parseUri(object.getString(LAUNCH_INTENT_KEY), 0);
                    String pn = launchIntent.getPackage();
                    if (pn == null) {
                        pn = launchIntent.getComponent().getPackageName();
                    }
                    if (packageNames.contains(pn)) {
                        newStringsIter.remove();
                    }
                } catch (org.json.JSONException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                } catch (java.net.URISyntaxException e) {
                    Log.d(TAG, "Exception reading shortcut to remove: " + e);
                }
            }
            sharedPrefs.edit().putStringSet(APPS_PENDING_INSTALL, new HashSet<String>(newStrings)).commit();
        }
    }
}

From source file:org.ESLM.Parser.JSONProtoLessonParser.java

private void parseLesson() throws BadFormedJSONExerciseException {
    JSONTokener tokener = new JSONTokener(reader);
    JSONObject jsonLesson = new JSONObject(tokener);
    String title = jsonLesson.optString("title", "Untitled Lesson");
    JSONArray jsonExercises = jsonLesson.optJSONArray("exercises");
    Instruction[] exercises = parseExercises(jsonExercises);
    parsedLesson = new ProtoLesson(title);
    for (Instruction instruction : exercises)
        parsedLesson.addExercise(instruction);
}

From source file:com.freshplanet.nativeExtensions.C2DMBroadcastReceiver.java

/**
 * Get the parameters from the message and create a notification from it.
 * @param context/*from  w w w. j a v a2  s.co m*/
 * @param intent
 */
public void handleMessage(Context context, Intent intent) {
    try {
        registerResources(context);
        extractColors(context);

        FREContext ctxt = C2DMExtension.context;

        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        // icon is required for notification.
        // @see http://developer.android.com/guide/practices/ui_guidelines/icon_design_status_bar.html

        int icon = notificationIcon;
        long when = System.currentTimeMillis();

        // json string

        String parameters = intent.getStringExtra("parameters");
        String facebookId = null;
        JSONObject object = null;
        if (parameters != null) {
            try {
                object = (JSONObject) new JSONTokener(parameters).nextValue();
            } catch (Exception e) {
                Log.d(TAG, "cannot parse the object");
            }
        }
        if (object != null && object.has("facebookId")) {
            facebookId = object.getString("facebookId");
        }

        CharSequence tickerText = intent.getStringExtra("tickerText");
        CharSequence contentTitle = intent.getStringExtra("contentTitle");
        CharSequence contentText = intent.getStringExtra("contentText");

        Intent notificationIntent = new Intent(context, Class.forName(context.getPackageName() + ".AppEntry"));

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        Notification notification = new Notification(icon, tickerText, when);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

        RemoteViews contentView = new RemoteViews(context.getPackageName(), customLayout);

        contentView.setTextViewText(customLayoutTitle, contentTitle);
        contentView.setTextViewText(customLayoutDescription, contentText);

        contentView.setTextColor(customLayoutTitle, notification_text_color);
        contentView.setFloat(customLayoutTitle, "setTextSize",
                notification_title_size_factor * notification_text_size);
        contentView.setTextColor(customLayoutDescription, notification_text_color);
        contentView.setFloat(customLayoutDescription, "setTextSize",
                notification_description_size_factor * notification_text_size);

        if (facebookId != null) {
            Log.d(TAG, "bitmap not null");
            CreateNotificationTask cNT = new CreateNotificationTask();
            cNT.setParams(customLayoutImageContainer, NotifId, nm, notification, contentView);
            String src = "http://graph.facebook.com/" + facebookId + "/picture?type=normal";
            URL url = new URL(src);
            cNT.execute(url);
        } else {
            Log.d(TAG, "bitmap null");
            contentView.setImageViewResource(customLayoutImageContainer, customLayoutImage);
            notification.contentView = contentView;
            nm.notify(NotifId, notification);
        }
        NotifId++;

        if (ctxt != null) {
            parameters = parameters == null ? "" : parameters;
            ctxt.dispatchStatusEventAsync("COMING_FROM_NOTIFICATION", parameters);
        }

    } catch (Exception e) {
        Log.e(TAG, "Error activating application:", e);
    }
}

From source file:org.everit.json.schema.InvalidObjectInArrayTest.java

private JSONObject readObject(final String fileName) {
    return new JSONObject(new JSONTokener(
            getClass().getResourceAsStream("/org/everit/json/schema/invalidobjectinarray/" + fileName)));
}

From source file:com.aliyun.openservices.odps.console.commands.logview.GetTaskDetailsAction.java

private List<FuxiJob> loadJobsFromStream(InputStream in) throws ODPSConsoleException {
    JSONTokener tokener = new JSONTokener(new BufferedReader(new InputStreamReader(in)));
    try {/*from   w  ww .ja v  a2  s . co  m*/
        JSONObject obj = new JSONObject(tokener);
        ArrayList<FuxiJob> jobs = new ArrayList<FuxiJob>();
        JSONObject mapReduceJson;
        try {
            mapReduceJson = obj.getJSONObject("mapReduce");
        } catch (JSONException e) {
            return jobs;
        }
        JSONArray jobsJson = mapReduceJson.getJSONArray("jobs");
        for (int i = 0; i < jobsJson.length(); i++) {
            jobs.add(getFuxiJobFromJson(jobsJson.getJSONObject(i)));
        }
        return jobs;
    } catch (JSONException e) {
        e.printStackTrace();
        throw new ODPSConsoleException("Bad json format");
    }
}

From source file:charitypledge.Pledge.java

public void JsonImport() {

    try {//  w  w w. ja v  a 2s . c o  m
        InputStream foo = new FileInputStream(JSONFile);
        JSONTokener t = new JSONTokener(foo);
        JSONObject jsonObj = new JSONObject(t);
        foo.close();
        JSONArray jsonList = jsonObj.getJSONArray("contributors");
        for (int i = 0; i < jsonList.length(); i++) {
            // loop array
            JSONObject objects = jsonList.getJSONObject(i);
            String nameField = objects.getString("name");
            String typeField = objects.getString("charity");
            String contributionField = objects.getString("contribution");
            // Add row to jTable
            loadPledgeTable(nameField, typeField, contributionField);
        }
    } catch (FileNotFoundException e) {
        JSONWriter jsonWriter;
        try {
            jsonWriter = new JSONWriter(new FileWriter(JSONFile));
            jsonWriter.object();
            jsonWriter.key("contributors");
            jsonWriter.array();
            jsonWriter.endArray();
            jsonWriter.endObject();
            //jsonWriter.close();
            tableRefresh();
        } catch (IOException f) {
            f.printStackTrace();
        } catch (JSONException g) {
            g.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:charitypledge.Pledge.java

public void JsonWrite(String[] args) {

    String[] values = args;//from   ww w .j  a v  a2s  .  co m
    JSONObject obj = new JSONObject();
    JSONArray objArray = new JSONArray();
    try {
        if (args == null || values.length == 0) {
            throw new Exception("Noting to write to file");
        } else {
            String title = "";
            String value = "";

            for (int i = (values.length - 1); i >= 0; i--) {
                if ((i % 2) == 0) {
                    title = values[i];
                    obj.put(title, value);
                } else {
                    value = values[i];
                }
            }
            objArray.put(obj);
        }

        try {
            try {
                InputStream foo = new FileInputStream(JSONFile);
                JSONTokener t = new JSONTokener(foo);
                JSONObject json = new JSONObject(t);
                foo.close();
                FileWriter file = new FileWriter(JSONFile);
                json.append("contributors", obj);
                file.write(json.toString(5));
                file.close();
                tableRefresh();
            } catch (FileNotFoundException e) {
                JSONWriter jsonWriter;
                try {
                    jsonWriter = new JSONWriter(new FileWriter(JSONFile));
                    jsonWriter.object();
                    jsonWriter.key("contributors");
                    jsonWriter.array();
                    jsonWriter.endArray();
                    jsonWriter.endObject();
                    InputStream foo = new FileInputStream(JSONFile);
                    JSONTokener t = new JSONTokener(foo);
                    JSONObject json = new JSONObject(t);
                    foo.close();
                    FileWriter file = new FileWriter(JSONFile);
                    json.append("contributors", obj);
                    file.write(json.toString(5));
                    file.close();
                    tableRefresh();
                } catch (IOException f) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        int pic = JOptionPane.ERROR_MESSAGE;
        JOptionPane.showMessageDialog(null, e, "", pic);
    }
}

From source file:com.android.aft.AFCuteJsonParser.AFCuteJsonParser.java

public AFCuteJsonParserResult parse(Context ctx, String json_str) {
    dbg.d("Launch parsing");

    if (json_str == null)
        return new AFCuteJsonParserResult(1, "Json parsing failed: input data is 'null'");

    // Low level parsing of the json string data
    Object json;//  ww w .j  a v  a 2 s .co m
    try {
        json = new JSONTokener(json_str).nextValue();
    } catch (JSONException e) {
        dbg.e("Json parsing failed", e);
        return new AFCuteJsonParserResult(1, "Json parsing failed");
    }

    if (hasDebug)
        dbg.d("Json result object: " + json);

    // Create the context
    AFCuteJsonParserContext context = new AFCuteJsonParserContext();
    context.setApplicationContext(ctx);
    context.setCurrent(new AFJsonValue(AFJsonValue.ROOT_VALUE_NAME, json));

    // Read root element (and recursively all values)
    read_root(context);

    // Return parsing result
    return context.getResult();
}

From source file:com.nosoop.json.VDF.java

/**
 * Attempts to convert what is assumed to be a String containing VDF text
 * into the JSON format.//from  ww  w. ja v  a2  s .  c o  m
 *
 * @param string Input data, assumed to be in the Valve Data Format.
 * @param convertArrays Whether or not to convert VDF-formatted arrays into
 * JSONArrays.
 * @return A JSON representation of the assumed-VDF data.
 * @throws JSONException Parse exception?
 */
public static JSONObject toJSONObject(String string, boolean convertArrays) throws JSONException {
    return toJSONObject(new JSONTokener(string), convertArrays);
}