Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

In this page you can find the example usage for org.json JSONObject optString.

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:com.sciencehighgames.electronicstructure.util.SkuDetails.java

public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException {
    mItemType = itemType;//ww  w. j a v a2 s.  c  o m
    mJson = jsonSkuDetails;
    JSONObject o = new JSONObject(mJson);
    mSku = o.optString("productId");
    mType = o.optString("type");
    mPrice = o.optString("price");
    mTitle = o.optString("title");
    mDescription = o.optString("description");
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public KeywordMapping(String mapFN) {
    file = new File(mapFN);

    // try to load the file, but it's OK if it fails
    JSONObject json = null;/* www  . j  a  va 2  s. c  o m*/
    try {
        Reader rdr = new FileReader(file);
        json = new JSONObject(new JSONTokener(rdr));
        rdr.close();
    } catch (JSONException ex) {
        Util.writeln("NOTE: reading file " + file.getAbsolutePath() + " failed: " + ex.getMessage());
    } catch (IOException ex) {
        return;
    } // includes file not found, which is OK

    try {
        for (JSONObject obj : json.optJSONArrayEmpty("identifiers").toObjectArray()) {
            Identifier id = new Identifier();
            id.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            id.prefix = obj.optString("prefix");
            identifiers.add(id);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("textBlocks").toObjectArray()) {
            TextBlock txt = new TextBlock();
            txt.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            txt.title = obj.optString("title");
            textBlocks.add(txt);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("properties").toObjectArray()) {
            Property prop = new Property();
            prop.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            prop.propURI = obj.optString("propURI");
            prop.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            properties.add(prop);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("values").toObjectArray()) {
            Value val = new Value();
            val.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            val.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            val.valueURI = obj.optString("valueURI");
            val.propURI = obj.optString("propURI");
            val.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            values.add(val);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("literals").toObjectArray()) {
            Literal lit = new Literal();
            lit.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            lit.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            lit.propURI = obj.optString("propURI");
            lit.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            literals.add(lit);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("references").toObjectArray()) {
            Reference ref = new Reference();
            ref.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            ref.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            ref.prefix = obj.optString("prefix");
            ref.propURI = obj.optString("propURI");
            ref.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            references.add(ref);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("assertions").toObjectArray()) {
            Assertion asrt = new Assertion();
            asrt.propURI = obj.optString("propURI");
            asrt.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            asrt.valueURI = obj.optString("valueURI");
            assertions.add(asrt);
        }
    } catch (JSONException ex) {
        Util.writeln("NOTE: parsing error");
        ex.printStackTrace();
        Util.writeln(
                "*** Execution will continue, but part of the mapping has not been loaded and may be overwritten.");
    }
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache)
        throws JSONException, IOException {
    String uniqueID = null;/*from  www.  j av a2 s.co  m*/
    List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>();
    List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>();
    Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>();
    JSONArray jsonAnnot = new JSONArray();
    final String SEP = "::";

    // assertions: these always supply a term
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI));
        obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest)));
        obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI));
        jsonAnnot.put(obj);

        String hash = asrt.propURI + SEP + asrt.valueURI + SEP
                + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest));
        gotAnnot.add(hash);
    }

    // go through the columns one at a time
    for (String key : keydata.keySet()) {
        String data = keydata.getString(key);

        Identifier id = findIdentifier(key);
        if (id != null) {
            if (uniqueID == null)
                uniqueID = id.prefix + data;
            continue;
        }

        TextBlock tblk = findTextBlock(key);
        if (tblk != null) {
            if (Util.isBlank(tblk.title))
                linesTitle.add(data);
            else
                linesBlock.add(tblk.title + ": " + data);
        }

        Value val = findValue(key, data);
        if (val != null) {
            if (Util.isBlank(val.valueURI)) {
                linesSkipped.add(key + ": " + data);
            } else {
                String hash = val.propURI + SEP + val.valueURI + SEP
                        + (val.groupNest == null ? "" : String.join(SEP, val.groupNest));
                if (gotAnnot.contains(hash))
                    continue;

                JSONObject obj = new JSONObject();
                obj.put("propURI", ModelSchema.expandPrefix(val.propURI));
                obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest)));
                obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI));
                jsonAnnot.put(obj);
                gotAnnot.add(hash);
                linesProcessed.add(key + ": " + data);
            }
            continue;
        }

        Literal lit = findLiteral(key, data);
        if (lit != null) {
            String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest))
                    + SEP + data;
            if (gotLiteral.contains(hash))
                continue;

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(lit.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest)));
            obj.put("valueLabel", data);
            jsonAnnot.put(obj);
            gotLiteral.add(hash);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        Reference ref = findReference(key, data);
        if (ref != null) {
            Pattern ptn = Pattern.compile(ref.valueRegex);
            Matcher m = ptn.matcher(data);
            if (!m.matches() || m.groupCount() < 1)
                throw new IOException(
                        "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group.");

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(ref.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest)));
            obj.put("valueLabel", ref.prefix + m.group(1));
            jsonAnnot.put(obj);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        // probably shouldn't get this far, but just in case
        linesSkipped.add(key + ": " + data);
    }

    // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes
    for (int n = 0; n < jsonAnnot.length(); n++) {
        JSONObject obj = jsonAnnot.getJSONObject(n);
        String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI");
        if (valueURI == null)
            continue;
        String[] groupNest = obj.getJSONArray("groupNest").toStringArray();
        Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI),
                groupNest);
        if (assnList.length == 0)
            continue;
        SchemaTree tree = treeCache.get(assnList[0]);
        if (tree == null)
            continue;

        Set<String> exclusion = new HashSet<>();
        for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent)
            exclusion.add(node.uri);
        if (exclusion.size() == 0)
            continue;

        for (int i = jsonAnnot.length() - 1; i >= 0; i--)
            if (i != n) {
                obj = jsonAnnot.getJSONObject(i);
                if (!obj.has("valueURI"))
                    continue;
                if (!propURI.equals(obj.getString("propURI")))
                    continue;
                if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray()))
                    continue;
                if (!exclusion.contains(obj.getString("valueURI")))
                    continue;
                jsonAnnot.remove(i);
            }
    }

    /*String text = "";
    if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n";
    if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n";
    text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/

    List<String> sections = new ArrayList<>();
    if (linesTitle.size() > 0)
        sections.add(String.join(" / ", linesTitle));
    if (linesBlock.size() > 0)
        sections.add(String.join("\n", linesBlock));
    sections.add("#### IMPORTED ####");
    if (linesSkipped.size() > 0)
        sections.add("SKIPPED:\n" + String.join("\n", linesSkipped));
    if (linesProcessed.size() > 0)
        sections.add("PROCESSED:\n" + String.join("\n", linesProcessed));
    String text = String.join("\n\n", sections);

    JSONObject assay = new JSONObject();
    assay.put("uniqueID", uniqueID);
    assay.put("text", text);
    assay.put("schemaURI", schema.getSchemaPrefix());
    assay.put("annotations", jsonAnnot);
    return assay;
}

From source file:com.sudhirkhanger.andpress.rest.WordPressAsyncTask.java

private ArrayList<Post> jsonConvertor(String postJsonStr) {
    ArrayList<Post> postArrayList = new ArrayList<>();

    try {/*from   w w  w .j ava2  s.  c o m*/
        JSONArray baseJsonArray = new JSONArray(postJsonStr);
        int numberOfItems = baseJsonArray.length();

        for (int i = 0; i < numberOfItems; i++) {
            JSONObject item = baseJsonArray.getJSONObject(i);

            int id = item.optInt(ID);

            JSONObject titleObject = item.getJSONObject(TITLE);
            String title = titleObject.optString(RENDERED);

            JSONObject contentObject = item.getJSONObject(CONTENT);
            String content = contentObject.optString(RENDERED);

            String featured_media = item.optString(FEATURED_MEDIA);

            Post post = new Post(id, title, featured_media, content);
            postArrayList.add(post);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Problem parsing the WordPress JSON results", e);
    }
    return postArrayList;
}

From source file:com.chaosinmotion.securechat.server.commands.RemoveDevice.java

public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String deviceid = requestParams.optString("deviceid");

    /*// w w w.j a v a  2s.c  o m
     * Delete device. We only delete if it is also ours.
     */
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM Devices " + "WHERE userid = ? AND deviceuuid = ?");
        ps.setInt(1, userinfo.getUserID());
        ps.setString(2, deviceid);
        ps.execute();

        return true;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:com.basetechnology.s0.agentserver.field.LocationField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("date"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    String defaultValue = fieldJson.has("default_value") ? fieldJson.optString("default_value") : null;
    String minValue = fieldJson.has("min_value") ? fieldJson.optString("min_value") : null;
    String maxValue = fieldJson.has("max_value") ? fieldJson.optString("max_value") : null;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new LocationField(symbolTable, name, label, description, defaultValue, minValue, maxValue,
            nominalWidth, compute);/* w ww.  j a  v  a  2 s  . c o m*/
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

public void publishWithoutDialog(Activity activity, FbSimplePost post, final NewObjectListener listener) {

    facebookRequest(activity, "me/feed", paramsForPost(post), "POST", true, new RequestAdapter() {

        public void onComplete(JSONObject jsonResponse, Object state) {
            listener.onComplete(jsonResponse.optString("id"));
        }//from  w  w w  . j  a v a 2 s  .com

        public void onFail(Throwable thr, Object state) {
            listener.onFail(thr);
        }

        public void onCancel() {
            listener.onCancel();
        }
    });
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

public void createEvent(Activity activity, FbEvent event, final NewObjectListener listener) {

    facebookRequest(activity, "me/events", paramsForEvent(event), "POST", true, new RequestAdapter() {

        public void onComplete(JSONObject jsonResponse, Object state) {
            listener.onComplete(jsonResponse.optString("id"));
        }//from   w w w  . ja  v  a 2  s.  c o m

        public void onFail(Throwable thr, Object state) {
            listener.onFail(thr);
        }

        public void onCancel() {
            listener.onCancel();
        }
    });
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

public void commentPost(final Activity activity, final String postId, final NewObjectListener listener) {

    if (!mFacebook.isSessionValid()) {
        login(activity, new SimpleRequestListener() {

            public void onComplete() {
                commentPost(activity, postId, listener);
            }/*ww w  .  ja va  2 s . co  m*/

            public void onFail(Throwable thr) {
                listener.onFail(thr);
            }

            public void onCancel() {
                listener.onCancel();
            }
        });
    } else {

        final FbTextDialog dialog = new FbTextDialog(activity);
        dialog.setDialogListener(new DialogListener() {

            public void onComplete(Bundle values) {

                final ProgressDialog spinner = new ProgressDialog(activity);
                spinner.setMessage(spinner.getContext().getString(R.string.loading));
                spinner.setCancelable(false);
                spinner.show();

                facebookRequest(activity, postId + "/comments", values, "POST", true, new RequestAdapter() {

                    public void onFail(Throwable thr, Object state) {
                        listener.onFail(thr);
                        spinner.dismiss();
                        dialog.dismiss();
                    }

                    public void onComplete(JSONObject jsonResponse, Object state) {
                        listener.onComplete(jsonResponse.optString("id"));
                        spinner.dismiss();
                        dialog.dismiss();
                    }

                    public void onCancel() {
                        listener.onCancel();
                        spinner.dismiss();
                        dialog.dismiss();
                    }
                });
            }

            public void onFacebookError(FacebookError e) {
                listener.onFail(e);
            }

            public void onError(DialogError e) {
                listener.onFail(e);
            }

            public void onCancel() {
                listener.onCancel();
            }
        });

        dialog.show();
    }
}

From source file:br.com.indigo.android.facebook.SocialFacebook.java

public void publish(final Activity activity, final FbSimplePost post, final String pageId,
        final NewObjectListener listener) {

    if (!mFacebook.isSessionValid()) {

        login(activity, new SimpleRequestListener() {

            public void onFail(Throwable thr) {
                listener.onFail(thr);/*from   w  ww.j a v a 2  s  . c  o  m*/
            }

            public void onCancel() {
                listener.onCancel();
            }

            public void onComplete() {
                publish(activity, post, pageId, listener);
            }
        });
    } else {

        final FbTextDialog dialog = new FbTextDialog(activity);
        dialog.setTitle(R.string.dialog_post_to_wall_title);
        dialog.setPlaceHolder(R.string.dialog_post_to_wall_placeholder);

        dialog.setDialogListener(new DialogListener() {

            public void onComplete(Bundle values) {

                final ProgressDialog spinner = new ProgressDialog(activity);
                spinner.setMessage(spinner.getContext().getString(R.string.loading));
                spinner.setCancelable(false);
                spinner.show();

                Bundle params = paramsForPost(post);
                params.putAll(values);

                facebookRequest(activity, pageId + "/feed", params, "POST", true, new RequestAdapter() {

                    public void onFail(Throwable thr, Object state) {
                        listener.onFail(thr);
                        spinner.dismiss();
                        dialog.dismiss();
                    }

                    public void onComplete(JSONObject jsonResponse, Object state) {
                        listener.onComplete(jsonResponse.optString("id"));
                        spinner.dismiss();
                        dialog.dismiss();
                    }

                    public void onCancel() {
                        listener.onCancel();
                        spinner.dismiss();
                        dialog.dismiss();
                    }
                });
            }

            public void onFacebookError(FacebookError e) {
                listener.onFail(e);
            }

            public void onError(DialogError e) {
                listener.onFail(e);
            }

            public void onCancel() {
                listener.onCancel();
            }
        });

        dialog.show();
    }
}