Example usage for org.json JSONTokener nextClean

List of usage examples for org.json JSONTokener nextClean

Introduction

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

Prototype

public char nextClean() throws JSONException 

Source Link

Document

Get the next char in the string, skipping whitespace and comments (slashslash, slashstar, and hash).

Usage

From source file:com.gistlabs.mechanize.document.json.JsonDocument.java

@Override
protected void loadPage() throws Exception {
    try {//from   w w  w  .  j  a  v a 2 s . co  m
        JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(getInputStream()));
        char nextClean = jsonTokener.nextClean();
        jsonTokener.back();

        switch (nextClean) {
        case '{':
            this.json = new ObjectNodeImpl(new JSONObject(jsonTokener));
            break;
        case '[':
            this.json = new ArrayNodeImpl(new JSONArray(jsonTokener));
            break;
        default:
            throw new IllegalStateException(
                    String.format("Error processing token=%s from request=%s", nextClean, this.getRequest()));
        }
    } catch (Exception e) {
        throw MechanizeExceptionFactory.newException(e);
    }
}

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

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

    while (x.more()) {
        char c = x.nextClean();

        switch (c) {
        case QUOTE:
            // Case that it is a String key, expect its value next.
            String key = x.nextString(QUOTE);

            char ctl = x.nextClean();
            if (ctl == SLASH) {
                if (x.next() == SLASH) {
                    // Comment -- ignore the rest of the line.
                    x.skipTo(NEWLINE);
                    ctl = x.nextClean();
                }
            }

            // Case that the next thing is another String value; add.
            if (ctl == QUOTE) {
                String value = getVDFValue(x, QUOTE);
                jo.put(key, value);
            } // Or a nested KeyValue pair. Parse then add.
            else if (ctl == L_BRACE) {
                jo.put(key, toJSONObject(x, convertArrays));
            }

            // TODO Add support for bracketed tokens?

            break;
        case R_BRACE:
            // Case that we are done parsing this KeyValue collection.
            // Return it (back to the calling toJSONObject() method).
            return jo;
        case '\0':
            // Disregard null character.
            break;
        case SLASH:
            if (x.next() == SLASH) {
                // It's a comment. Skip to the next line.
                x.skipTo(NEWLINE);
                break;
            }
        default:
            String fmtError = "Unexpected character \'%s\'";
            throw x.syntaxError(String.format(fmtError, c));
        }
    }

    if (convertArrays) {
        return convertVDFArrays(jo);
    }

    return jo;
}

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  w ww  .j a  v a 2  s. c o  m
@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: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();/*  w ww  . ja  va  2 s.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:org.araqne.confdb.file.Importer.java

private void parseCollections(JSONTokener t, Manifest manifest, List<ConfigChange> configChanges)
        throws JSONException, ParseException, IOException {
    Object key = t.nextValue();/*from w w  w . ja  v  a 2 s  .  c  om*/
    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;
    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  v  a  2s .  c  o  m

    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:com.jskaleel.xml.JSONObject.java

/**
 * Construct a JSONObject from a JSONTokener.
 *
 * @param x//from  ww w .  ja  v  a 2  s . c o m
 *            A JSONTokener object containing the source string.
 * @throws JSONException
 *             If there is a syntax error in the source string or a
 *             duplicated key.
 * @throws org.json.JSONException 
 */
public JSONObject(JSONTokener x) throws JSONException, org.json.JSONException {
    this();
    char c;
    String key;

    if (x.nextClean() != '{') {
        throw x.syntaxError("A JSONObject text must begin with '{'");
    }
    for (;;) {
        c = x.nextClean();
        switch (c) {
        case 0:
            throw x.syntaxError("A JSONObject text must end with '}'");
        case '}':
            return;
        default:
            x.back();
            key = x.nextValue().toString();
        }

        // The key is followed by ':'.

        c = x.nextClean();
        if (c != ':') {
            throw x.syntaxError("Expected a ':' after a key");
        }
        this.putOnce(key, x.nextValue());

        // Pairs are separated by ','.

        switch (x.nextClean()) {
        case ';':
        case ',':
            if (x.nextClean() == '}') {
                return;
            }
            x.back();
            break;
        case '}':
            return;
        default:
            throw x.syntaxError("Expected a ',' or '}'");
        }
    }
}

From source file:org.apache.oltu.oauth2.ext.dynamicreg.server.request.JSONHttpServletRequestWrapper.java

public Map<String, String[]> getParameterMap() {
    if (!bodyRead) {
        String body = readJsonBody();

        final JSONTokener x = new JSONTokener(body);
        char c;//from   w ww .  j  a  v a2 s  . c  om
        String key;

        if (x.nextClean() != '{') {
            throw new OAuthRuntimeException(format(
                    "String '%s' is not a valid JSON object representation, a JSON object text must begin with '{'",
                    body));
        }
        for (;;) {
            c = x.nextClean();
            switch (c) {
            case 0:
                throw new OAuthRuntimeException(format(
                        "String '%s' is not a valid JSON object representation, a JSON object text must end with '}'",
                        body));
            case '}':
                return Collections.unmodifiableMap(parameters);
            default:
                x.back();
                key = x.nextValue().toString();
            }

            /*
             * The key is followed by ':'. We will also tolerate '=' or '=>'.
             */
            c = x.nextClean();
            if (c == '=') {
                if (x.next() != '>') {
                    x.back();
                }
            } else if (c != ':') {
                throw new OAuthRuntimeException(format(
                        "String '%s' is not a valid JSON object representation, expected a ':' after the key '%s'",
                        body, key));
            }
            Object value = x.nextValue();

            // guard from null values
            if (value != null) {
                if (value instanceof JSONArray) { // only plain simple arrays in this version
                    JSONArray array = (JSONArray) value;
                    String[] values = new String[array.length()];
                    for (int i = 0; i < array.length(); i++) {
                        values[i] = String.valueOf(array.get(i));
                    }
                    parameters.put(key, values);
                } else {
                    parameters.put(key, new String[] { String.valueOf(value) });
                }
            }

            /*
             * Pairs are separated by ','. We will also tolerate ';'.
             */
            switch (x.nextClean()) {
            case ';':
            case ',':
                if (x.nextClean() == '}') {
                    return Collections.unmodifiableMap(parameters);
                }
                x.back();
                break;
            case '}':
                return Collections.unmodifiableMap(parameters);
            default:
                throw new OAuthRuntimeException(format(
                        "String '%s' is not a valid JSON object representation, Expected a ',' or '}", body));
            }
        }
    }

    return Collections.unmodifiableMap(parameters);
}