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:org.boris.xlloop.http.JSONCodec.java

public static XLoper decodeXLoper(Reader r) throws IOException, JSONException {
    JSONTokener t = new JSONTokener(r);
    JSONObject jo = new JSONObject(t);
    return decode(jo);
}

From source file:com.apecat.shoppingadvisor.scan.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//from  w w w. j  a  v  a 2  s . co m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e);
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:com.github.pffy.chinese.freq.ChineseFrequency.java

private JSONObject loadIdx(String str) {

    JSONObject jo;/*  w  ww .  j a  v a2  s.  c  o m*/
    InputStream is;

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

    return jo;
}

From source file:org.apache.hadoop.hive.hbase.LazyHBaseRow.java

/**
 * Get the field out of the row without checking whether parsing is needed.
 * This is called by both getField and getFieldsAsList.
 * @param fieldID  The id of the field starting from 0.
 * @param nullSequence  The sequence representing NULL value.
 * @return  The value of the field/*from w  ww.j  a  v a2s . c  om*/
 */
private Object uncheckedGetField(int fieldID) {
    if (!getFieldInited()[fieldID]) {
        getFieldInited()[fieldID] = true;

        ByteArrayRef ref = null;
        String columnName = hbaseColumns.get(fieldID);
        if (columnName.equals(HBaseSerDe.HBASE_KEY_COL)) {
            ref = new ByteArrayRef();
            ref.setData(rowResult.getRow());
        } else {
            if (columnName.endsWith(":")) {
                // it is a column family
                ((LazyHBaseCellMap) getFields()[fieldID]).init(rowResult, columnName);
            } else if (columnName.endsWith("]")) {
                String newColumnName = columnName.split("\\[")[0];
                Object val = "";
                if (getField(fieldID) instanceof LazyJsonArray) {
                    ((LazyJsonArray) getField(fieldID)).init(new JSONArray());
                }
                if (rowResult.containsKey(newColumnName)) {
                    String jsonString = new String(rowResult.get(newColumnName).getValue());
                    ref = new ByteArrayRef();
                    ref.setData("".getBytes());
                    try {
                        JSONObject jso;
                        jso = new JSONObject(new JSONTokener(jsonString));
                        val = extractFromJson(columnName, jso);
                        if (val != null) {
                            if (val instanceof JSONArray) {
                                ((LazyJsonArray) getFields()[fieldID]).init((JSONArray) val);
                            } else {
                                ref.setData(val.toString().getBytes());
                            }
                        }
                    } catch (JSONException e) {
                    }
                }
            } else {
                // it is a column

                if (rowResult.containsKey(columnName)) {
                    ref = new ByteArrayRef();
                    ref.setData(rowResult.get(columnName).getValue());
                } else {
                    return null;
                }
            }
        }
        if (ref != null) {
            getFields()[fieldID].init(ref, 0, ref.getData().length);
        }
    }
    return getFields()[fieldID].getObject();
}

From source file:com.android.i18n.addressinput.JsoMap.java

/**
 * Construct a JsoMap object given some json text. This method directly evaluates the String
 * that you pass in; no error or safety checking is performed, so be very careful about the
 * source of your data.//from ww w  .ja  va  2s .  co m
 *
 * @param json JSON text describing an address format
 * @return a JsoMap object made from the supplied JSON.
 */
static JsoMap buildJsoMap(String json) throws JSONException {
    return new JsoMap(new JSONTokener(json));
}

From source file:org.mozilla.fennec_satyanarayan.LauncherShortcuts.java

public void onListItemClick(int id) {
    HashMap<String, String> map = mWebappsList.get(id);

    String uri = map.get("uri").toString();
    String title = map.get("title").toString();
    String appKey = map.get("appKey").toString();
    String favicon = map.get("favicon").toString();

    File manifestFile = new File(mWebappsFolder, appKey + "/manifest.json");

    // Parse the contents into a string
    String manifestJson = new String();
    try {//from www  . j av  a  2  s  . com
        BufferedReader in = new BufferedReader(new FileReader(manifestFile));
        String line = new String();

        while ((line = in.readLine()) != null) {
            manifestJson += line;
        }
    } catch (IOException e) {
    }

    try {
        JSONObject manifest = (JSONObject) new JSONTokener(manifestJson).nextValue();
        uri += manifest.getString("launch_path");
    } catch (JSONException e) {
    }

    Intent shortcutintent = new Intent("org.mozilla.gecko.WEBAPP");
    shortcutintent.setClass(this, App.class);
    shortcutintent.putExtra("args", "--webapp=" + uri);

    Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutintent);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int size;
    switch (dm.densityDpi) {
    case DisplayMetrics.DENSITY_MEDIUM:
        size = 48;
        break;
    case DisplayMetrics.DENSITY_HIGH:
        size = 72;
        break;
    default:
        size = 72;
    }

    Bitmap bitmap = BitmapFactory.decodeFile(favicon);
    if (bitmap != null) {
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
        intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, scaledBitmap);
    }

    // Now, return the result to the launcher
    setResult(RESULT_OK, intent);
    finish();
}

From source file:net.dv8tion.jda.core.requests.Response.java

protected Response(final okhttp3.Response response, final int code, final String message, final long retryAfter,
        final Set<String> cfRays) {
    this.rawResponse = response;
    this.code = code;
    this.message = message;
    this.exception = null;
    this.retryAfter = retryAfter;
    this.cfRays = cfRays;

    if (response == null || response.body().contentLength() == 0) {
        this.object = null;
        return;/*from ww w. j a va 2s.co m*/
    }

    InputStream body = null;
    BufferedReader reader = null;
    try {
        body = Requester.getBody(response);
        // this doesn't add overhead as org.json would do that itself otherwise
        reader = new BufferedReader(new InputStreamReader(body));
        char begin; // not sure if I really like this... but we somehow have to get if this is an object or an array
        int mark = 1;
        do {
            reader.mark(mark++);
            begin = (char) reader.read();
        } while (Character.isWhitespace(begin));

        reader.reset();

        if (begin == '{')
            this.object = new JSONObject(new JSONTokener(reader));
        else if (begin == '[')
            this.object = new JSONArray(new JSONTokener(reader));
        else
            this.object = reader.lines().collect(Collectors.joining());
    } catch (final Exception e) {
        throw new RuntimeException("An error occurred while parsing the response for a RestAction", e);
    } finally {
        try {
            body.close();
            reader.close();
        } catch (NullPointerException | IOException ignored) {
        }
    }
}

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

@Test
public void validateEmptyObject() {

    JSONObject jsonSchema = new JSONObject(new JSONTokener(
            MetaSchemaTest.class.getResourceAsStream("/org/everit/json/schema/json-schema-draft-04.json")));

    JSONObject jsonSubject = new JSONObject(
            "{\n" + "  \"type\": \"object\",\n" + "  \"properties\": {}\n" + "}");

    Schema schema = SchemaLoader.load(jsonSchema);
    schema.validate(jsonSubject);//from www.java2  s. c o  m
}

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

@Test
public void validateMetaSchema() {

    JSONObject jsonSchema = new JSONObject(new JSONTokener(
            MetaSchemaTest.class.getResourceAsStream("/org/everit/json/schema/json-schema-draft-04.json")));

    JSONObject jsonSubject = new JSONObject(new JSONTokener(
            MetaSchemaTest.class.getResourceAsStream("/org/everit/json/schema/json-schema-draft-04.json")));

    Schema schema = SchemaLoader.load(jsonSchema);
    schema.validate(jsonSubject);//from  www.  j a  va  2 s  . co m
}

From source file:org.fabrican.extension.variable.provider.VariableProviderProxy.java

public Properties getVariables(FabricEngineInfo engineInfo, StackInfo stackInfo, ComponentInfo componentInfo) {

    MapContext jc = new MapContext();
    jc.set("engineInfo", engineInfo);
    jc.set("stackInfo", stackInfo);
    jc.set("componentInfo", componentInfo);
    String p = evaluate(getPrimaryKey(), jc);
    String s = evaluate(getSecondaryKey(), jc);
    ;/*w  w w  . j  av a 2 s.  c o m*/

    if (getServerURL() == null) {
        throw new IllegalArgumentException("serverURL is not set");
    }
    String u = getServerURL();
    try {
        u += "?primary=" + (p == null ? "" : URLEncoder.encode(p.trim(), "utf-8"));
        u += "&secondary=" + (s == null ? "" : URLEncoder.encode(s.trim(), "utf-8"));
    } catch (UnsupportedEncodingException e) {
        // we always have "UTF-8" but anyway
        throw new RuntimeException("utf-8 not supported", e);
    }
    InputStream is = null;
    try {
        URL url = new URL(u);
        URLConnection c = url.openConnection();
        is = c.getInputStream();
        JSONTokener tokener = new JSONTokener(new InputStreamReader(is, "utf-8"));
        JSONObject jObj = new JSONObject(tokener);
        Properties r = new Properties();
        @SuppressWarnings("unchecked")
        Iterator<String> keys = jObj.keys();
        while (keys.hasNext()) {
            String k = keys.next();
            r.put(k, jObj.getString(k));
        }
        String msg = "no variables";
        if (r.size() > 0) {
            msg = r.toString();
        }
        ContainerUtils.getLogger(this).fine(
                "Provided " + msg + " to Engine " + engineInfo.getUsername() + "-" + engineInfo.getInstance());
        return r;
    } catch (IOException ioe) {
        throw new RuntimeException("failed to connection to web server", ioe);
    } catch (JSONException je) {
        throw new RuntimeException("failed to parse response from web server", je);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (Exception e) {

        }
    }
}