Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:com.axinom.drm.quickstart.activity.SampleChooserActivity.java

private void makeMoviesRequest() {
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, API_CATALOG, null,
            new Response.Listener<JSONArray>() {
                @Override//ww  w.  j a v a  2 s  . co  m
                public void onResponse(JSONArray response) {
                    // Adding video URLs and names to lists from json array response.
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject jsonObject = response.getJSONObject(i);
                            mVideoUrls.add(jsonObject.getString("url"));
                            mVideoNames.add(jsonObject.getString("name"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(),
                            android.R.layout.simple_list_item_1, mVideoNames) {
                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {
                            View view = super.getView(position, convertView, parent);
                            TextView textView = (TextView) view.findViewById(android.R.id.text1);
                            textView.setTextColor(Color.BLACK);
                            return view;
                        }
                    };
                    mListView.setAdapter(adapter);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, "Movies json was not loaded with error: " + error.getMessage());
                }
            });
    BaseApp.requestQueue.add(request);
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * MetaWeblog requests processing./*from  ww  w . j av  a 2 s .co  m*/
 * 
 * @param request the specified http servlet request
 * @param response the specified http servlet response
 * @param context the specified http request context
 */
@RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST)
public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response,
        final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);

    String responseContent = null;
    try {
        final ServletInputStream inputStream = request.getInputStream();
        final String xml = IOUtils.toString(inputStream, "UTF-8");
        final JSONObject requestJSONObject = XML.toJSONObject(xml);

        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);
        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);

        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");

        if (METHOD_DELETE_POST.equals(methodName)) {
            params.remove(0); // Removes the first argument "appkey"
        }

        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value")
                .getString("string");
        final JSONObject user = userQueryService.getUserByEmail(userEmail);
        if (null == user) {
            throw new Exception("No user[email=" + userEmail + "]");
        }

        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string");
        if (!user.getString(User.USER_PASSWORD).equals(userPwd)) {
            throw new Exception("Wrong password");
        }

        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value")
                    .getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            addArticle(article);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(article.getString(Keys.OBJECT_ID))
                            .append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            article.put(Keys.OBJECT_ID, postId);

            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(postId).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            articleMgmtService.removeArticle(postId);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><boolean>")
                            .append(true).append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        responseContent = "";
        final StringBuilder stringBuilder = new StringBuilder(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><fault><value><struct>")
                        .append("<member><name>faultCode</name><value><int>500</int></value></member>")
                        .append("<member><name>faultString</name><value><string>").append(e.getMessage())
                        .append("</string></value></member></struct></value></fault></methodResponse>");
        responseContent = stringBuilder.toString();
    }

    renderer.setContent(responseContent);
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Parses the specified method call for an article.
 * /*from  www. j  a  v  a2s  . c  o m*/
 * @param methodCall the specified method call
 * @return article
 * @throws Exception exception 
 */
private JSONObject parsetPost(final JSONObject methodCall) throws Exception {
    final JSONObject ret = new JSONObject();

    final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
    final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct");
    final JSONArray members = post.getJSONArray("member");

    for (int i = 0; i < members.length(); i++) {
        final JSONObject member = members.getJSONObject(i);
        final String name = member.getString("name");

        if ("dateCreated".equals(name)) {
            final JSONObject preference = preferenceQueryService.getPreference();

            final String dateString = member.getJSONObject("value").getString("dateTime.iso8601");
            Date date = null;
            try {
                date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString);
            } catch (final ParseException e) {
                LOGGER.log(Level.WARNING,
                        "Parses article create date failed with ISO8601, retry to parse with pattern[yyyy-MM-dd'T'HH:mm:ss]");
                final String timeZoneId = preference.getString(Preference.TIME_ZONE_ID);
                final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
                final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
                format.setTimeZone(timeZone);
                date = format.parse(dateString);
            }
            ret.put(Article.ARTICLE_CREATE_DATE, date);
        } else if ("title".equals(name)) {
            ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string"));
        } else if ("description".equals(name)) {
            final String content = member.getJSONObject("value").getString("string");
            ret.put(Article.ARTICLE_CONTENT, content);

            final String plainTextContent = Jsoup.parse(content).text();
            if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH));
            } else {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent);
            }
        } else if ("categories".equals(name)) {
            final StringBuilder tagBuilder = new StringBuilder();

            final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data");
            if (0 == data.length()) {
                throw new Exception("At least one Tag");
            }

            final Object value = data.get("value");
            if (value instanceof JSONArray) {
                final JSONArray tags = (JSONArray) value;
                for (int j = 0; j < tags.length(); j++) {
                    final String tagTitle = tags.getJSONObject(j).getString("string");
                    tagBuilder.append(tagTitle);

                    if (j < tags.length() - 1) {
                        tagBuilder.append(",");
                    }
                }
            } else {
                final JSONObject tag = (JSONObject) value;
                tagBuilder.append(tag.getString("string"));
            }

            ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString());
        }
    }

    final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean")
            ? true
            : false;
    ret.put(Article.ARTICLE_IS_PUBLISHED, publish);

    ret.put(Article.ARTICLE_COMMENTABLE, true);
    ret.put(Article.ARTICLE_VIEW_PWD, "");

    return ret;
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Builds a post (post struct) with the specified post id.
 * //ww w  .  j ava 2 s  .c om
 * @param postId the specified post id
 * @return blog info XML
 * @throws Exception exception 
 */
private String buildPost(final String postId) throws Exception {
    final StringBuilder stringBuilder = new StringBuilder();

    final JSONObject result = articleQueryService.getArticle(postId);

    if (null == result) {
        throw new Exception("Not found article[id=" + postId + "]");
    }

    final JSONObject article = result.getJSONObject(Article.ARTICLE);

    final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE);
    final String articleTitle = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE));

    stringBuilder.append("<struct>");

    stringBuilder.append("<member><name>dateCreated</name>").append("<value><dateTime.iso8601>")
            .append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(createDate))
            .append("</dateTime.iso8601></value></member>");

    stringBuilder.append("<member><name>description</name>").append("<value>")
            .append(StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT)))
            .append("</value></member>");

    stringBuilder.append("<member><name>title</name>").append("<value>").append(articleTitle)
            .append("</value></member>");

    stringBuilder.append("<member><name>categories</name>").append("<value><array><data>");
    final JSONArray tags = article.getJSONArray(Article.ARTICLE_TAGS_REF);
    for (int i = 0; i < tags.length(); i++) {
        final String tagTitle = tags.getJSONObject(i).getString(Tag.TAG_TITLE);
        stringBuilder.append("<value>").append(tagTitle).append("</value>");
    }
    stringBuilder.append("</data></array></value></member></struct>");

    return stringBuilder.toString();
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Builds recent posts (array of post structs) with the specified 
 * fetch size./*from   w w  w.j a v a 2s . c  o  m*/
 * 
 * @param fetchSize the specified fetch size
 * @return blog info XML
 * @throws Exception exception 
 */
private String buildRecentPosts(final int fetchSize) throws Exception {

    final StringBuilder stringBuilder = new StringBuilder();

    final List<JSONObject> recentArticles = articleQueryService.getRecentArticles(fetchSize);

    for (final JSONObject article : recentArticles) {
        final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE);
        final String articleTitle = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE));

        stringBuilder.append("<value><struct>");

        stringBuilder.append("<member><name>dateCreated</name>").append("<value><dateTime.iso8601>")
                .append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(createDate))
                .append("</dateTime.iso8601></value></member>");

        stringBuilder.append("<member><name>description</name>").append("<value>")
                .append(StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT)))
                .append("</value></member>");

        stringBuilder.append("<member><name>title</name>").append("<value>").append(articleTitle)
                .append("</value></member>");

        stringBuilder.append("<member><name>postid</name>").append("<value>")
                .append(article.getString(Keys.OBJECT_ID)).append("</value></member>");

        stringBuilder.append("<member><name>categories</name>").append("<value><array><data>");
        final String tagTitles = article.getString(Article.ARTICLE_TAGS_REF);
        final String[] tagTitleArray = tagTitles.split(",");
        for (int i = 0; i < tagTitleArray.length; i++) {
            final String tagTitle = tagTitleArray[i];
            stringBuilder.append("<value>").append(tagTitle).append("</value>");
        }
        stringBuilder.append("</data></array></value></member>");

        stringBuilder.append("</struct></value>");
    }

    return stringBuilder.toString();
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Builds categories (array of category info structs) with the specified 
 * preference.//  w ww. ja  v a 2 s  .  c  om
 * 
 * @param preference the specified preference
 * @return blog info XML
 * @throws Exception exception 
 */
private String buildCategories(final JSONObject preference) throws Exception {
    final String blogHost = "http://" + preference.getString(Preference.BLOG_HOST);

    final StringBuilder stringBuilder = new StringBuilder();

    final List<JSONObject> tags = tagQueryService.getTags();
    for (final JSONObject tag : tags) {
        final String tagTitle = StringEscapeUtils.escapeXml(tag.getString(Tag.TAG_TITLE));
        final String tagId = tag.getString(Keys.OBJECT_ID);

        stringBuilder.append("<value><struct>");

        stringBuilder.append("<member><name>description</name>").append("<value>").append(tagTitle)
                .append("</value></member>");

        stringBuilder.append("<member><name>title</name>").append("<value>").append(tagTitle)
                .append("</value></member>");

        stringBuilder.append("<member><name>categoryid</name>").append("<value>").append(tagId)
                .append("</value></member>");

        stringBuilder.append("<member><name>htmlUrl</name>").append("<value>").append(blogHost).append("/tags/")
                .append(tagTitle).append("</value></member>");

        stringBuilder.append("<member><name>rsslUrl</name>").append("<value>").append(blogHost)
                .append("/tag-articles-rss.do?oId=").append(tagId).append("</value></member>");

        stringBuilder.append("</struct></value>");
    }

    return stringBuilder.toString();
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Builds blog info struct with the specified preference.
 * // w ww  . j  a  v a  2  s  . c om
 * @param preference the specified preference
 * @return blog info XML
 * @throws JSONException json exception 
 */
private String buildBlogInfo(final JSONObject preference) throws JSONException {
    final String blogId = preference.getString(Keys.OBJECT_ID);

    final String blogTitle = StringEscapeUtils.escapeXml(preference.getString(Preference.BLOG_TITLE));

    final String blogURL = "http://" + preference.getString(Preference.BLOG_HOST);

    final StringBuilder stringBuilder = new StringBuilder("<member><name>blogid</name><value>").append(blogId)
            .append("</value></member>");
    stringBuilder.append("<member><name>url</name><value>").append(blogURL).append("</value></member>");
    stringBuilder.append("<member><name>blogName</name><value>").append(blogTitle).append("</value></member>");

    return stringBuilder.toString();
}

From source file:io.selendroid.server.FindElementHandlerTest.java

public void assertThatFindElementResponseHasCorrectFormat() throws Exception {
    HttpResponse response = executeCreateSessionRequest();
    SelendroidAssert.assertResponseIsRedirect(response);
    JSONObject session = parseJsonResponse(response);
    String sessionId = session.getString("sessionId");
    Assert.assertFalse(sessionId.isEmpty());

    JSONObject payload = new JSONObject();
    payload.put("using", "id");
    payload.put("value", "my_button_bar");

    String url = "http://" + host + ":" + port + "/wd/hub/session/" + sessionId + "/element";
    HttpResponse element = executeRequestWithPayload(url, HttpMethod.POST, payload.toString());
    SelendroidAssert.assertResponseIsOk(element);
}

From source file:de.dmxcontrol.programmer.EntityProgrammer.java

public static EntityProgrammer Receive(JSONObject o) {
    EntityProgrammer entity = new EntityProgrammer();
    try {/* ww  w . j  a va 2 s  .com*/
        if (o.getString("Type").equals(NetworkID)) {
            int number = o.getInt("Number");
            String name = o.getString("Name");
            entity.setId(number);
            entity.setName(name.replace(NetworkID + ": ", ""), true);
            entity.guid = o.getString("GUID");
        }
    } catch (Exception e) {
        Log.e("UDP Listener: ", e.getMessage());
        DMXControlApplication.SaveLog();
    }
    o = null;
    if (o == null) {
        entity.runChangeListener();
    }
    return entity;
}

From source file:uk.org.rivernile.edinburghbustracker.android.Application.java

/**
 * Check for updates to the bus stop database. This may happen automatically
 * if 24 hours have elapsed since the last check, or if the user has forced
 * the action. If a database update is found, then the new database is
 * downloaded and placed in the correct location.
 * /*w  w  w .  j a v  a 2  s .co  m*/
 * @param context The context.
 * @param force True if the user forced the check, false if not.
 */
public static void checkForDBUpdates(final Context context, final boolean force) {
    // Check to see if the user wants their database automatically updated.
    final SharedPreferences sp = context.getSharedPreferences(PreferencesActivity.PREF_FILE, 0);
    final boolean autoUpdate = sp.getBoolean(PREF_DATABASE_AUTO_UPDATE, true);
    final SharedPreferences.Editor edit = sp.edit();

    // Continue to check if the user has enabled it, or a check has been
    // forced (from the Preferences).
    if (autoUpdate || force) {
        if (!force) {
            // If it has not been forced, check the last update time. It is
            // only checked once per day. Abort if it is too soon.
            long lastCheck = sp.getLong("lastUpdateCheck", 0);
            if ((System.currentTimeMillis() - lastCheck) < 86400000)
                return;
        }

        // Construct the checking URL.
        final StringBuilder sb = new StringBuilder();
        sb.append(DB_API_CHECK_URL);
        sb.append(ApiKey.getHashedKey());
        sb.append("&random=");
        // A random number is used so networks don't cache the HTTP
        // response.
        sb.append(random.nextInt());
        try {
            // Do connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                // Read the incoming data.
                int data;
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String topoId;
        try {
            // Parse the JSON and get the topoId from it.
            final JSONObject jo = new JSONObject(sb.toString());
            topoId = jo.getString("topoId");
        } catch (JSONException e) {
            return;
        }

        // If there's topoId then it cannot continue.
        if (topoId == null || topoId.length() == 0)
            return;

        // Get the current topoId from the database.
        final BusStopDatabase bsd = BusStopDatabase.getInstance(context.getApplicationContext());
        final String dbTopoId = bsd.getTopoId();

        // If the topoIds match, write our check time to SharedPreferences.
        if (topoId.equals(dbTopoId)) {
            edit.putLong("lastUpdateCheck", System.currentTimeMillis());
            edit.commit();
            if (force) {
                // It was forced, alert the user there is no update
                // available.
                Looper.prepare();
                Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
                Looper.loop();
            }
            return;
        }

        // There is an update available. Empty the StringBuilder then create
        // the URL to get the new database information.
        sb.setLength(0);
        sb.append(DB_UPDATE_CHECK_URL);
        sb.append(random.nextInt());
        sb.append("&key=");
        sb.append(ApiKey.getHashedKey());

        try {
            // Connection stuff.
            final URL url = new URL(sb.toString());
            sb.setLength(0);
            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                final BufferedInputStream is = new BufferedInputStream(conn.getInputStream());

                if (!url.getHost().equals(conn.getURL().getHost())) {
                    is.close();
                    conn.disconnect();
                    return;
                }

                int data;
                // Read the incoming data.
                while ((data = is.read()) != -1) {
                    sb.append((char) data);
                }
            } finally {
                // Whether there's an error or not, disconnect.
                conn.disconnect();
            }
        } catch (MalformedURLException e) {
            return;
        } catch (IOException e) {
            return;
        }

        String dbUrl, schemaVersion, checksum;
        try {
            // Get the data from tje returned JSON.
            final JSONObject jo = new JSONObject(sb.toString());
            dbUrl = jo.getString("db_url");
            schemaVersion = jo.getString("db_schema_version");
            topoId = jo.getString("topo_id");
            checksum = jo.getString("checksum");
        } catch (JSONException e) {
            // There was an error parsing the JSON, it cannot continue.
            return;
        }

        // Make sure the returned schema name is compatible with the one
        // the app uses.
        if (!BusStopDatabase.SCHEMA_NAME.equals(schemaVersion))
            return;
        // Some basic sanity checking on the parameters.
        if (topoId == null || topoId.length() == 0)
            return;
        if (dbUrl == null || dbUrl.length() == 0)
            return;
        if (checksum == null || checksum.length() == 0)
            return;

        // Make sure an update really is available.
        if (!topoId.equals(dbTopoId)) {
            // Update the database.
            updateStopsDB(context, dbUrl, checksum);
        } else if (force) {
            // Tell the user there is no update available.
            Looper.prepare();
            Toast.makeText(context, R.string.bus_stop_db_no_updates, Toast.LENGTH_LONG).show();
            Looper.loop();
        }

        // Write to the SharedPreferences the last update time.
        edit.putLong("lastUpdateCheck", System.currentTimeMillis());
        edit.commit();
    }
}