Example usage for org.json JSONTokener nextValue

List of usage examples for org.json JSONTokener nextValue

Introduction

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

Prototype

public Object nextValue() throws JSONException 

Source Link

Document

Get the next value.

Usage

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

private Object loadJsonFile(final File file) {

    Object subject = null;//from  w ww  . j a  va 2s .  c  o m

    try {
        JSONTokener jsonTok = new JSONTokener(new FileInputStream(file));

        // Determine if we have a single JSON object or an array of them
        Object jsonTest = jsonTok.nextValue();
        if (jsonTest instanceof JSONObject) {
            // The message contains a single JSON object
            subject = jsonTest;
        } else if (jsonTest instanceof JSONArray) {
            // The message contains a JSON array
            subject = jsonTest;
        }
    } catch (JSONException e) {
        throw new RuntimeException("failed to parse subject json file", e);
    } catch (FileNotFoundException e) {
        throw new UncheckedIOException(e);
    }
    return subject;
}

From source file:org.cfg4j.source.context.propertiesprovider.JsonBasedPropertiesProvider.java

/**
 * Get {@link Properties} for a given {@code inputStream} treating it as a JSON file.
 *
 * @param inputStream input stream representing JSON file
 * @return properties representing values from {@code inputStream}
 * @throws IllegalStateException when unable to read properties
 *///from   ww  w  .j a  va2 s . com
@Override
public Properties getProperties(InputStream inputStream) {
    requireNonNull(inputStream);

    Properties properties = new Properties();

    try {

        JSONTokener tokener = new JSONTokener(inputStream);
        if (tokener.end()) {
            return properties;
        }
        if (tokener.nextClean() == '"') {
            tokener.back();
            properties.put("content", tokener.nextValue().toString());
        } else {
            tokener.back();
            JSONObject obj = new JSONObject(tokener);

            Map<String, Object> yamlAsMap = convertToMap(obj);
            properties.putAll(flatten(yamlAsMap));
        }

        return properties;

    } catch (Exception e) {
        throw new IllegalStateException("Unable to load json configuration from provided stream", e);
    }
}

From source file:net.majorkernelpanic.spydroid.api.RequestHandler.java

/**
 * Executes a batch of requests and returns all the results
 * @param request Contains a json containing one or more requests
 * @return A JSON to send back//  ww w .j a  v a  2 s  .co m
 */
static public String handle(String request) {
    StringBuilder response = new StringBuilder();
    JSONTokener tokener = new JSONTokener(request);

    try {
        Object token = tokener.nextValue();

        response.append("{");

        // More than one request to execute
        if (token instanceof JSONArray) {
            JSONArray array = (JSONArray) token;
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = (JSONObject) array.get(i);
                response.append("\"" + object.getString("action") + "\":");
                exec(object, response);
                if (i != array.length() - 1)
                    response.append(",");
            }
            // Only One request
        } else if (token instanceof JSONObject) {
            JSONObject object = (JSONObject) token;
            response.append("\"" + object.getString("action") + "\":");
            exec(object, response);
        }

        response.append("}");

    } catch (Exception e) {
        // Pokemon, gotta catch'em all !
        Log.e(TAG, "Invalid request: " + request);
        e.printStackTrace();
        return "INVALID REQUEST";
    }

    Log.d(TAG, "Request: " + request);
    Log.d(TAG, "Answer: " + response.toString());

    return response.toString();
}

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

private void parseCollections(JSONTokener t, Manifest manifest, List<ConfigChange> configChanges)
        throws JSONException, ParseException, IOException {
    Object key = t.nextValue();
    if (!key.equals("collections"))
        throw new ParseException("collections should be placed after metadata: token is " + key, -1);

    // "collections":{"COLNAME":["list",[...]]}
    t.nextClean(); // :
    t.nextClean(); // {

    if (t.nextClean() == '}')
        return;/*from   w  ww.  j av  a2 s. c  o  m*/
    t.back();

    int i = 0;
    List<String> importColNames = new ArrayList<String>();
    while (true) {
        if (i++ != 0)
            t.nextClean();

        String colName = (String) t.nextValue();
        importColNames.add(colName);
        CollectionEntry collectionEntry = checkCollectionEntry(manifest, colName);
        manifest.add(collectionEntry);

        t.nextTo('[');
        t.nextClean();

        // type token (should be 'list')
        t.nextValue();
        t.nextTo("[");
        t.nextClean();

        // check empty config list
        char c = t.nextClean();
        if (c == ']') {
            t.nextClean(); // last ']'
            char marker = t.nextClean(); // ',' or '}'
            if (marker == '}')
                break;
            else
                t.back();

            continue;
        }

        t.back();

        int collectionId = collectionEntry.getId();
        RevLogWriter writer = null;
        try {
            File logFile = new File(db.getDbDirectory(), "col" + collectionId + ".log");
            File datFile = new File(db.getDbDirectory(), "col" + collectionId + ".dat");

            writer = new RevLogWriter(logFile, datFile);

            while (true) {
                @SuppressWarnings("unchecked")
                Object doc = removeType((List<Object>) parse((JSONArray) t.nextValue()));
                ConfigEntry configEntry = writeConfigEntry(writer, doc, collectionId);
                configChanges.add(new ConfigChange(CommitOp.CreateDoc, colName, collectionEntry.getId(),
                        configEntry.getDocId()));
                manifest.add(configEntry);

                // check next list item
                char delimiter = t.nextClean();
                if (delimiter == ']')
                    break;
            }
        } finally {
            if (writer != null)
                writer.close();
        }

        // end of list
        t.nextClean();

        char delimiter = t.nextClean();
        if (delimiter == '}')
            break;
    }

    for (String colName : db.getCollectionNames()) {
        if (importColNames.contains(colName))
            continue;
        configChanges.add(new ConfigChange(CommitOp.DropCol, colName, 0, 0));
        manifest.remove(new CollectionEntry(db.getCollectionId(colName), colName));
    }
}

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

private Map<String, Object> parseMetadata(JSONTokener x) throws JSONException, IOException {
    if (x.nextClean() != '{') {
        throw x.syntaxError("A JSONObject text must begin with '{'");
    }//from w  w  w . ja  va 2  s .c om

    Object key = x.nextValue();
    if (!key.equals("metadata"))
        throw x.syntaxError("confdb metadata should be placed first");

    x.nextClean();
    return parse((JSONObject) x.nextValue());
}

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.  c  om
    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:com.chaosinmotion.securechat.network.SCNetwork.java

/**
 * Internal method to parse result from server
 * @param is Input stream from server/*ww  w. j a  va 2s  .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();
}

From source file:com.mattermost.service.Promise.java

void onResult(T r, String error) {
    MattermostApplication.handler.post(new Runnable() {
        @Override//from w  w  w.  j av a2s .  c  o  m
        public void run() {
            try {
                if (busy != null) {
                    busy.dismiss();
                }
                busy = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    });

    result = r;

    if (error != null) {
        // lets parse...
        error = error.trim();
        if (error.startsWith("{") && error.endsWith("}")) {
            try {
                JSONTokener tokener = new JSONTokener(error);
                errorJson = (JSONObject) tokener.nextValue();
                if (errorJson.has("message")) {
                    this.error = errorJson.optString("message");
                }
            } catch (Exception ex) {
                // ignore...
                this.error = error;
            }
        } else {
            this.error = error;
        }
    }

    MattermostApplication.handler.post(new Runnable() {
        @Override
        public void run() {
            for (IResultListener<T> resultListener : next) {
                try {
                    resultListener.onResult(Promise.this);
                } catch (Exception ex) {
                    MattermostApplication.logError(ex);
                }
            }
        }
    });

}

From source file:com.github.michalbednarski.intentslab.browser.FetcherManager.java

static Fetcher unserializeFetcher(String serialized) {
    JSONTokener tokenizer = new JSONTokener(serialized);
    try {/*from  ww w . ja  v  a 2  s  .  co  m*/
        JSONObject jsonObject = (JSONObject) tokenizer.nextValue();
        String type = jsonObject.getString("_type");
        for (Fetcher.Descriptor descriptor : FETCHER_REGISTRY) {
            if (descriptor.internalName.equals(type)) {
                return descriptor.unserializeFromJSON(jsonObject);
            }
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    throw new RuntimeException("Unknown _type");
}

From source file:com.tnc.android.graphite.utils.GraphiteConnection.java

private static void getTargetsRecursive(ArrayList<Target> targets, String serverUrl, String targetFilter,
        int levels) throws Exception {
    BufferedReader reader = getReader(serverUrl + TARGETS_PARAM_STRING + targetFilter);

    String line;/* w  w  w .  ja v a  2s . c  o  m*/
    if ((line = reader.readLine()) != null) {
        JSONTokener jTok = new JSONTokener(line);
        if (jTok.more()) {
            JSONArray array = (JSONArray) jTok.nextValue();
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.getJSONObject(i);
                String id = obj.getString("id");
                int exp = obj.getInt("expandable");
                Target t = new Target();
                t.setHash(hash);
                t.setName(id);
                if (1 == exp) {
                    t.setExpandable(true);
                }
                targets.add(t);
                if (1 == exp && 1 < levels) {
                    // Recursively parse the branch
                    getTargetsRecursive(targets, serverUrl, id + ".*", levels - 1);
                }
            }
        }
    }
}