Search in sources :

Example 86 with JSONArray

use of org.json.JSONArray in project solo by b3log.

the class RepairProcessor method repairTagArticleCounter.

/**
     * Repairs tag article counter.
     *
     * @param context the specified context
     */
@RequestProcessing(value = "/fix/tag-article-counter-repair.do", method = HTTPRequestMethod.GET)
@Transactional
public void repairTagArticleCounter(final HTTPRequestContext context) {
    final TextHTMLRenderer renderer = new TextHTMLRenderer();
    context.setRenderer(renderer);
    try {
        final JSONObject result = tagRepository.get(new Query());
        final JSONArray tagArray = result.getJSONArray(Keys.RESULTS);
        final List<JSONObject> tags = CollectionUtils.jsonArrayToList(tagArray);
        for (final JSONObject tag : tags) {
            final String tagId = tag.getString(Keys.OBJECT_ID);
            final JSONObject tagArticleResult = tagArticleRepository.getByTagId(tagId, 1, Integer.MAX_VALUE);
            final JSONArray tagArticles = tagArticleResult.getJSONArray(Keys.RESULTS);
            final int tagRefCnt = tagArticles.length();
            int publishedTagRefCnt = 0;
            for (int i = 0; i < tagRefCnt; i++) {
                final JSONObject tagArticle = tagArticles.getJSONObject(i);
                final String articleId = tagArticle.getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
                final JSONObject article = articleRepository.get(articleId);
                if (null == article) {
                    tagArticleRepository.remove(tagArticle.optString(Keys.OBJECT_ID));
                    continue;
                }
                if (article.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
                    publishedTagRefCnt++;
                }
            }
            tag.put(Tag.TAG_REFERENCE_COUNT, tagRefCnt);
            tag.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, publishedTagRefCnt);
            tagRepository.update(tagId, tag);
            LOGGER.log(Level.INFO, "Repaired tag[title={0}, refCnt={1}, publishedTagRefCnt={2}]", new Object[] { tag.getString(Tag.TAG_TITLE), tagRefCnt, publishedTagRefCnt });
        }
        renderer.setContent("Repair sucessfully!");
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        renderer.setContent("Repairs failed, error msg[" + e.getMessage() + "]");
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) TextHTMLRenderer(org.b3log.latke.servlet.renderer.TextHTMLRenderer) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing) Transactional(org.b3log.latke.repository.annotation.Transactional)

Example 87 with JSONArray

use of org.json.JSONArray in project solo by b3log.

the class SitemapProcessor method addNavigations.

/**
     * Adds navigations into the specified sitemap.
     * 
     * @param sitemap the specified sitemap
     * @throws Exception exception 
     */
private void addNavigations(final Sitemap sitemap) throws Exception {
    final JSONObject result = pageRepository.get(new Query());
    final JSONArray pages = result.getJSONArray(Keys.RESULTS);
    for (int i = 0; i < pages.length(); i++) {
        final JSONObject page = pages.getJSONObject(i);
        final String permalink = page.getString(Page.PAGE_PERMALINK);
        final URL url = new URL();
        // Just filters for user mistakes tolerance
        if (!permalink.contains("://")) {
            url.setLoc(Latkes.getServePath() + permalink);
        } else {
            url.setLoc(permalink);
        }
        sitemap.addURL(url);
    }
}
Also used : JSONObject(org.json.JSONObject) Query(org.b3log.latke.repository.Query) JSONArray(org.json.JSONArray) URL(org.b3log.solo.model.sitemap.URL)

Example 88 with JSONArray

use of org.json.JSONArray in project solo by b3log.

the class FeedProcessor method tagArticlesRSS.

/**
     * Tag articles RSS output.
     *
     * @param context the specified context
     * @throws IOException io exception
     */
@RequestProcessing(value = { "/tag-articles-rss.do" }, method = { HTTPRequestMethod.GET, HTTPRequestMethod.HEAD })
public void tagArticlesRSS(final HTTPRequestContext context) throws IOException {
    final HttpServletResponse response = context.getResponse();
    final HttpServletRequest request = context.getRequest();
    final RssRenderer renderer = new RssRenderer();
    context.setRenderer(renderer);
    final String queryString = request.getQueryString();
    if (Strings.isEmptyOrNull(queryString)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    final String oIdMap = queryString.split("&")[0];
    final String tagId = oIdMap.split("=")[1];
    final Channel channel = new Channel();
    try {
        final JSONObject tag = tagRepository.get(tagId);
        if (null == tag) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final String tagTitle = tag.getString(Tag.TAG_TITLE);
        final JSONObject preference = preferenceQueryService.getPreference();
        if (null == preference) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final String blogTitle = preference.getString(Option.ID_C_BLOG_TITLE);
        final String blogSubtitle = preference.getString(Option.ID_C_BLOG_SUBTITLE) + ", " + tagTitle;
        final int outputCnt = preference.getInt(Option.ID_C_FEED_OUTPUT_CNT);
        channel.setTitle(StringEscapeUtils.escapeXml(blogTitle));
        channel.setLastBuildDate(new Date());
        channel.setLink(Latkes.getServePath());
        channel.setAtomLink(Latkes.getServePath() + "/tag-articles-rss.do");
        channel.setGenerator("Solo, ver " + SoloServletListener.VERSION);
        final String localeString = preference.getString(Option.ID_C_LOCALE_STRING);
        final String country = Locales.getCountry(localeString).toLowerCase();
        final String language = Locales.getLanguage(localeString).toLowerCase();
        channel.setLanguage(language + '-' + country);
        channel.setDescription(blogSubtitle);
        final JSONObject tagArticleResult = tagArticleRepository.getByTagId(tagId, 1, outputCnt);
        final JSONArray tagArticleRelations = tagArticleResult.getJSONArray(Keys.RESULTS);
        if (0 == tagArticleRelations.length()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final List<JSONObject> articles = new ArrayList<JSONObject>();
        for (int i = 0; i < tagArticleRelations.length(); i++) {
            final JSONObject tagArticleRelation = tagArticleRelations.getJSONObject(i);
            final String articleId = tagArticleRelation.getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
            final JSONObject article = articleRepository.get(articleId);
            if (// Skips the unpublished article
            article.getBoolean(Article.ARTICLE_IS_PUBLISHED) && Strings.isEmptyOrNull(article.optString(Article.ARTICLE_VIEW_PWD))) {
                // Skips article with password
                articles.add(article);
            }
        }
        final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
        String authorName = "";
        if (!hasMultipleUsers && !articles.isEmpty()) {
            authorName = articleQueryService.getAuthor(articles.get(0)).getString(User.USER_NAME);
        }
        final boolean isFullContent = "fullContent".equals(preference.getString(Option.ID_C_FEED_OUTPUT_MODE));
        for (int i = 0; i < articles.size(); i++) {
            Item item = getItemForArticles(articles, hasMultipleUsers, authorName, isFullContent, i);
            channel.addItem(item);
        }
        renderer.setContent(channel.toString());
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Get tag article rss error", e);
        try {
            context.getResponse().sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
Also used : Channel(org.b3log.solo.model.feed.rss.Channel) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) RssRenderer(org.b3log.latke.servlet.renderer.RssRenderer) Date(java.util.Date) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Item(org.b3log.solo.model.feed.rss.Item) JSONObject(org.json.JSONObject) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 89 with JSONArray

use of org.json.JSONArray in project solo by b3log.

the class ArchiveDateArticleRepositoryImpl method getByArticleId.

@Override
public JSONObject getByArticleId(final String articleId) throws RepositoryException {
    final Query query = new Query();
    query.setFilter(new PropertyFilter(Article.ARTICLE + "_" + Keys.OBJECT_ID, FilterOperator.EQUAL, articleId));
    final JSONObject result = get(query);
    final JSONArray array = result.optJSONArray(Keys.RESULTS);
    if (0 == array.length()) {
        return null;
    }
    return array.optJSONObject(0);
}
Also used : Query(org.b3log.latke.repository.Query) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) PropertyFilter(org.b3log.latke.repository.PropertyFilter)

Example 90 with JSONArray

use of org.json.JSONArray in project solo by b3log.

the class ArchiveDateRepositoryImpl method getByArchiveDate.

@Override
public JSONObject getByArchiveDate(final String archiveDate) throws RepositoryException {
    long time = 0L;
    try {
        time = DateUtils.parseDate(archiveDate, new String[] { "yyyy/MM" }).getTime();
    } catch (final ParseException e) {
        LOGGER.log(Level.ERROR, "Can not parse archive date [" + archiveDate + "]", e);
        throw new RepositoryException("Can not parse archive date [" + archiveDate + "]");
    }
    LOGGER.log(Level.TRACE, "Archive date [{0}] parsed to time [{1}]", new Object[] { archiveDate, time });
    final Query query = new Query();
    query.setFilter(new PropertyFilter(ArchiveDate.ARCHIVE_TIME, FilterOperator.EQUAL, time)).setPageCount(1);
    final JSONObject result = get(query);
    final JSONArray array = result.optJSONArray(Keys.RESULTS);
    if (0 == array.length()) {
        return null;
    }
    return array.optJSONObject(0);
}
Also used : Query(org.b3log.latke.repository.Query) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) RepositoryException(org.b3log.latke.repository.RepositoryException) PropertyFilter(org.b3log.latke.repository.PropertyFilter) ParseException(java.text.ParseException)

Aggregations

JSONArray (org.json.JSONArray)1710 JSONObject (org.json.JSONObject)1191 JSONException (org.json.JSONException)738 ArrayList (java.util.ArrayList)323 IOException (java.io.IOException)243 Test (org.junit.Test)207 HashMap (java.util.HashMap)108 ClientException (edu.umass.cs.gnscommon.exceptions.client.ClientException)96 List (java.util.List)63 DefaultGNSTest (edu.umass.cs.gnsserver.utils.DefaultGNSTest)61 File (java.io.File)54 HashSet (java.util.HashSet)54 Date (java.util.Date)47 Query (org.b3log.latke.repository.Query)47 RandomString (edu.umass.cs.gnscommon.utils.RandomString)44 GraphObject (com.abewy.android.apps.klyph.core.graph.GraphObject)43 FileNotFoundException (java.io.FileNotFoundException)40 Map (java.util.Map)40 GuidEntry (edu.umass.cs.gnsclient.client.util.GuidEntry)36 VolleyError (com.android.volley.VolleyError)35