Example usage for org.json JSONTokener back

List of usage examples for org.json JSONTokener back

Introduction

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

Prototype

public void back() 

Source Link

Document

Back up one character.

Usage

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

@Override
protected void loadPage() throws Exception {
    try {/*from  w  w  w .  j  av a2s .  c  o  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: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
 *//*w  w  w . ja  va  2  s . c  om*/
@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

private void parseCollections(JSONTokener t, Manifest manifest, List<ConfigChange> configChanges)
        throws JSONException, ParseException, IOException {
    Object key = t.nextValue();/*w w  w . j ava2s.  co m*/
    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.official.json.CDL.java

/**
 * Get the next value. The value can be wrapped in quotes. The value can
 * be empty.//from w  w  w .j av a2s.c o m
 * @param x A JSONTokener of the source text.
 * @return The value string, or null if empty.
 * @throws JSONException if the quoted string is badly formed.
 */
private static String getValue(JSONTokener x) throws JSONException {
    char c;
    char q;
    StringBuffer sb;
    do {
        c = x.next();
    } while (c == ' ' || c == '\t');
    switch (c) {
    case 0:
        return null;
    case '"':
    case '\'':
        q = c;
        sb = new StringBuffer();
        for (;;) {
            c = x.next();
            if (c == q) {
                break;
            }
            if (c == 0 || c == '\n' || c == '\r') {
                throw x.syntaxError("Missing close quote '" + q + "'.");
            }
            sb.append(c);
        }
        return sb.toString();
    case ',':
        x.back();
        return "";
    default:
        x.back();
        return x.nextTo(',');
    }
}

From source file:com.jskaleel.xml.JSONObject.java

/**
 * Construct a JSONObject from a JSONTokener.
 *
 * @param x//  w  ww.  ja va2 s. co  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:com.auth0.api.internal.ApplicationInfoRequest.java

@Override
public void onResponse(Response response) throws IOException {
    if (!response.isSuccessful()) {
        String message = "Received app info failed response with code " + response.code() + " and body "
                + response.body().string();
        postOnFailure(new IOException(message));
        return;/*from   ww  w  .j a v a 2s  .c o m*/
    }
    try {
        String json = response.body().string();
        JSONTokener tokenizer = new JSONTokener(json);
        tokenizer.skipPast("Auth0.setClient(");
        if (!tokenizer.more()) {
            postOnFailure(tokenizer.syntaxError("Invalid App Info JSONP"));
            return;
        }
        Object nextValue = tokenizer.nextValue();
        if (!(nextValue instanceof JSONObject)) {
            tokenizer.back();
            postOnFailure(tokenizer.syntaxError("Invalid JSON value of App Info"));
        }
        JSONObject jsonObject = (JSONObject) nextValue;
        Log.d(TAG, "Obtained JSON object from JSONP: " + jsonObject);
        Application app = getReader().readValue(jsonObject.toString());
        postOnSuccess(app);
    } catch (JSONException | IOException e) {
        postOnFailure(new APIClientException("Failed to parse JSONP", e));
    }
}

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;//  www  . j  a v  a2s.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);
}