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:com.whizzosoftware.hobson.scheduler.ical.ICalTaskProviderTest.java

@Test
public void testEditEvent() throws Exception {
    File file = File.createTempFile("hob", ".ics");
    try {//from  www.j  av a2s . c o m
        String ical = "BEGIN:VCALENDAR\n" + "PRODID:-//Whizzo Software//Hobson 1.0//EN\n" + "VERSION:2.0\n"
                + "BEGIN:VEVENT\n" + "UID:15dee4fe-a841-4cf6-8d7f-76c3ad5492b1\n" + "DTSTART:20130714T170000Z\n"
                + "DTEND:20130714T170000Z\n" + "SUMMARY:My Task\n"
                + "COMMENT:[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Action','properties':{'message':'foo'}}]\n"
                + "END:VEVENT\n" + "END:VCALENDAR";

        String ical2 = "BEGIN:VCALENDAR\n" + "PRODID:-//Whizzo Software//Hobson 1.0//EN\n" + "VERSION:2.0\n"
                + "BEGIN:VEVENT\n" + "UID:15dee4fe-a841-4cf6-8d7f-76c3ad5492b1\n" + "DTSTART:20130714T170000Z\n"
                + "DTEND:20130714T170000Z\n" + "SUMMARY:My Edited Task\n"
                + "COMMENT:[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Edited Action','properties':{'message':'foobar'}}]\n"
                + "END:VEVENT\n" + "END:VCALENDAR";

        // write out ICS to temp file
        FileWriter fw = new FileWriter(file);
        fw.append(ical);
        fw.close();

        ICalTaskProvider p = new ICalTaskProvider("pluginId", null, null,
                TimeZone.getTimeZone("America/Denver"));
        p.setScheduleExecutor(new MockScheduledTaskExecutor());
        p.setScheduleFile(file);
        p.start();

        // make sure the task was created
        assertEquals(1, p.getTasks().size());

        // create task JSON
        JSONObject json = new JSONObject();
        json.put("name", "My Edited Task");
        JSONArray conds = new JSONArray();
        json.put("conditions", conds);
        JSONObject cond = new JSONObject();
        conds.put(cond);
        cond.put("start", "20130714T170000Z");
        JSONArray actions = new JSONArray();
        json.put("actions", actions);
        JSONObject action = new JSONObject();
        actions.put(action);
        action.put("pluginId", "com.whizzosoftware.hobson.server-api");
        action.put("actionId", "log");
        action.put("name", "My Edited Action");
        JSONObject props = new JSONObject();
        action.put("properties", props);
        props.put("message", "foobar");

        // update the task
        p.updateTask("15dee4fe-a841-4cf6-8d7f-76c3ad5492b1", json);

        assertTrue(file.exists());

        // read back file
        Calendar cal = new CalendarBuilder().build(new FileInputStream(file));
        assertEquals(1, cal.getComponents().size());
        VEvent c = (VEvent) cal.getComponents().get(0);
        assertEquals("My Edited Task", c.getProperty("SUMMARY").getValue());
        assertEquals("15dee4fe-a841-4cf6-8d7f-76c3ad5492b1", c.getProperty("UID").getValue());
        assertEquals("20130714T170000Z", c.getProperty("DTSTART").getValue());
        JSONArray aj = new JSONArray(new JSONTokener(c.getProperty("COMMENT").getValue()));
        assertEquals(1, aj.length());
        JSONObject cj = aj.getJSONObject(0);
        assertEquals("com.whizzosoftware.hobson.server-api", cj.getString("pluginId"));
        assertEquals("My Edited Action", cj.getString("name"));
        assertEquals("log", cj.getString("actionId"));
        assertTrue(cj.has("properties"));
        JSONObject pj = cj.getJSONObject("properties");
        assertEquals("foobar", pj.getString("message"));
    } finally {
        file.delete();
    }
}

From source file:com.example.wechatsample.library.http.JsonHttpResponseHandler.java

protected Object parseResponse(String responseBody) throws JSONException {
    Object result = null;/*w w  w .  j a v  a  2 s  . c  o m*/
    // trim the string to prevent start with blank, and test if the string
    // is valid JSON, because the parser don't do this :(. If Json is not
    // valid this will return null
    responseBody = responseBody.trim();
    if (responseBody.startsWith("{") || responseBody.startsWith("[")) {
        result = new JSONTokener(responseBody).nextValue();
    }
    if (result == null) {
        result = responseBody;
    }
    return result;
}

From source file:org.araqne.confdb.file.Importer.java

public void importData(InputStream is) throws IOException, ParseException {
    if (is == null)
        throw new IllegalArgumentException("import input stream cannot be null");

    logger.debug("araqne confdb: start import data");
    db.lock();//from  w w  w. ja  va2s . c  o  m

    try {
        JSONTokener t = new JSONTokener(new InputStreamReader(is, Charset.forName("utf-8")));

        Map<String, Object> metadata = parseMetadata(t);
        Integer version = (Integer) metadata.get("version");
        if (version != 1)
            throw new ParseException("unsupported confdb data format version: " + version, -1);

        Manifest manifest = db.getManifest(null);
        List<ConfigChange> configChanges = new ArrayList<ConfigChange>();

        char comma = t.nextClean();
        if (comma == ',')
            parseCollections(t, manifest, configChanges);

        writeManifestLog(manifest);
        writeChangeLog(configChanges, manifest.getId());
        logger.debug("araqne confdb: import complete");
    } catch (JSONException e) {
        throw new ParseException(e.getMessage(), 0);
    } finally {
        db.unlock();
    }
}

From source file:com.github.pffy.chinese.HanyuPinyin.java

private JSONObject loadIdx(String str) {

    JSONObject jo;// ww w .ja  va2 s  .  co  m
    InputStream is;

    is = HanyuPinyin.class.getResourceAsStream(str);
    jo = new JSONObject(new JSONTokener(is));

    return jo;
}

From source file:org.official.json.CDL.java

/**
 * Produce a JSONArray of JSONObjects from a comma delimited text string,
 * using the first row as a source of names.
 * @param string The comma delimited text.
 * @return A JSONArray of JSONObjects.//from  w  w w  . java  2 s  .c  o m
 * @throws JSONException
 */
public static JSONArray toJSONArray(String string) throws JSONException {
    return toJSONArray(new JSONTokener(string));
}

From source file:org.official.json.CDL.java

/**
 * Produce a JSONArray of JSONObjects from a comma delimited text string
 * using a supplied JSONArray as the source of element names.
 * @param names A JSONArray of strings./*from w  ww  . j  a v  a2  s.co  m*/
 * @param string The comma delimited text.
 * @return A JSONArray of JSONObjects.
 * @throws JSONException
 */
public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException {
    return toJSONArray(names, new JSONTokener(string));
}

From source file:org.sleeksnap.Configuration.java

/**
 * Load the configuration from a file//from  ww  w . ja  v a2 s.  c  o  m
 * 
 * @param file
 *            The file
 * @throws IOException
 *             If an error occurred while loading
 * @throws JSONException
 */
public void load(final File file) throws IOException {
    this.file = file;
    try {
        final FileInputStream fInput = new FileInputStream(file);
        try {
            config = new JSONObject(new JSONTokener(fInput));
        } finally {
            fInput.close();
        }
    } catch (final RuntimeException e) {
        throw new IOException(e);
    }
}

From source file:org.araqne.docxcod.test.FreeMarkerTest.java

@Test
public void UserDefMethodTest() throws Exception {
    InputStreamReader templateReader = null;
    InputStreamReader inputReader = null;
    Scanner scanner = null;/*from w w  w . j a  v a  2s  .com*/
    try {
        Configuration cfg = new Configuration();
        cfg.setObjectWrapper(new DefaultObjectWrapper());

        inputReader = new InputStreamReader(getClass().getResourceAsStream("/nestedListTest.in"));
        JSONTokener tokener = new JSONTokener(inputReader);
        Map<String, Object> rootMap = JsonHelper.parse((JSONObject) tokener.nextValue());

        MakeNewChartFunction makeNewChartFunction = new MakeNewChartFunction();
        rootMap.put("makeNewChart", makeNewChartFunction);

        templateReader = new InputStreamReader(getClass().getResourceAsStream("/userDefMethodTest.fpl"));
        Template t = new Template("UserDefMethodTest", templateReader, cfg);

        StringWriter out = new StringWriter();

        t.process(rootMap, out);

        scanner = new Scanner(getClass().getResourceAsStream("/userDefMethodTest.out"));
        String expectedOutput = scanner.useDelimiter("\\A").next();

        assertEquals(expectedOutput, out.toString());
        assertEquals(3, makeNewChartFunction.callCount);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        CloseableHelper.safeClose(inputReader);
        if (scanner != null)
            scanner.close();
    }
}

From source file:xanthanov.droid.funrun.PlaceSearcher.java

private List<GooglePlace> parseJsonResult(BufferedReader in) throws GmapException, IOException, JSONException {

    String jsonString = new String();
    String aLine = null;//from w  w w.ja  v  a 2  s . c  om
    List<GooglePlace> foundPlaces = new ArrayList<GooglePlace>();
    String status = null;
    JSONObject jObj = null;

    while ((aLine = in.readLine()) != null) {
        //   System.out.println(aLine);
        jsonString += aLine;
    }

    jObj = (JSONObject) new JSONTokener(jsonString).nextValue();
    status = jObj.getString("status");
    JSONArray results = jObj.getJSONArray("results");

    if (status.equals("ZERO_RESULTS")) {
        return foundPlaces; //Return empty array if no results 
    } else if (!status.equals("OK")) {
        throw new GmapException("Google Maps returned an error code:\n" + status);
    }

    for (int i = 0; i < results.length(); i++) {
        foundPlaces.add(parseGmapResult(results.getJSONObject(i)));
    }

    return foundPlaces;
}

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

/**
 * Internal method to parse result from server
 * @param is Input stream from server/*  w  w w .jav  a  2 s .  c o  m*/
 * @return JSON parsed result
 */
private static JSONObject parseResult(InputStream is) throws IOException, JSONException {
    ByteArrayOutputStream bais = new ByteArrayOutputStream();
    byte[] buffer = new byte[512];
    int len;

    while (0 < (len = is.read(buffer))) {
        bais.write(buffer, 0, len);
    }
    is.close();

    byte[] data = bais.toByteArray();
    if (data.length < 2)
        return new JSONObject(); // no return result
    String json = new String(data, "UTF-8");
    JSONTokener tokener = new JSONTokener(json);
    return (JSONObject) tokener.nextValue();
}