Search in sources :

Example 1 with Transactional

use of org.b3log.latke.repository.annotation.Transactional 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 2 with Transactional

use of org.b3log.latke.repository.annotation.Transactional in project symphony by b3log.

the class ArticleMgmtService method expireStick.

/**
 * Expires sticked articles.
 *
 * @throws ServiceException service exception
 */
@Transactional
public void expireStick() throws ServiceException {
    try {
        final Query query = new Query().setFilter(new PropertyFilter(Article.ARTICLE_STICK, FilterOperator.GREATER_THAN, 0L));
        final JSONArray articles = articleRepository.get(query).optJSONArray(Keys.RESULTS);
        if (articles.length() < 1) {
            return;
        }
        final long stepTime = Symphonys.getLong("stickArticleTime");
        final long now = System.currentTimeMillis();
        for (int i = 0; i < articles.length(); i++) {
            final JSONObject article = articles.optJSONObject(i);
            final long stick = article.optLong(Article.ARTICLE_STICK);
            if (stick >= Long.MAX_VALUE) {
                // Skip admin stick
                continue;
            }
            final long expired = stick + stepTime;
            if (expired < now) {
                article.put(Article.ARTICLE_STICK, 0L);
                articleRepository.update(article.optString(Keys.OBJECT_ID), article);
            }
        }
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Expires sticked articles failed", e);
        throw new ServiceException();
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONArray(org.json.JSONArray) Transactional(org.b3log.latke.repository.annotation.Transactional)

Example 3 with Transactional

use of org.b3log.latke.repository.annotation.Transactional in project symphony by b3log.

the class ArticleMgmtService method adminCancelStick.

/**
 * Admin cancels stick an article specified by the given article id.
 *
 * @param articleId the given article id
 * @throws ServiceException service exception
 */
@Transactional
public synchronized void adminCancelStick(final String articleId) throws ServiceException {
    try {
        final JSONObject article = articleRepository.get(articleId);
        if (null == article) {
            return;
        }
        article.put(Article.ARTICLE_STICK, 0L);
        articleRepository.update(articleId, article);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Admin cancel sticks an article[id=" + articleId + "] failed", e);
        throw new ServiceException(langPropsService.get("operationFailedLabel"));
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) Transactional(org.b3log.latke.repository.annotation.Transactional)

Example 4 with Transactional

use of org.b3log.latke.repository.annotation.Transactional in project symphony by b3log.

the class ArticleMgmtService method removeArticleByAdmin.

/**
 * Removes an article specified with the given article id. Calls this method will remove all existed data related
 * with the specified article forcibly.
 *
 * @param articleId the given article id
 */
@Transactional
public void removeArticleByAdmin(final String articleId) {
    try {
        final JSONObject article = articleRepository.get(articleId);
        if (null == article) {
            return;
        }
        Query query = new Query().setFilter(new PropertyFilter(Comment.COMMENT_ON_ARTICLE_ID, FilterOperator.EQUAL, articleId)).setPageCount(1);
        final JSONArray comments = commentRepository.get(query).optJSONArray(Keys.RESULTS);
        final int commentCnt = comments.length();
        for (int i = 0; i < commentCnt; i++) {
            final JSONObject comment = comments.optJSONObject(i);
            final String commentId = comment.optString(Keys.OBJECT_ID);
            commentRepository.removeComment(commentId);
        }
        final String authorId = article.optString(Article.ARTICLE_AUTHOR_ID);
        final JSONObject author = userRepository.get(authorId);
        author.put(UserExt.USER_ARTICLE_COUNT, author.optInt(UserExt.USER_ARTICLE_COUNT) - 1);
        userRepository.update(author.optString(Keys.OBJECT_ID), author);
        final String city = article.optString(Article.ARTICLE_CITY);
        final String cityStatId = city + "-ArticleCount";
        final JSONObject cityArticleCntOption = optionRepository.get(cityStatId);
        if (null != cityArticleCntOption) {
            cityArticleCntOption.put(Option.OPTION_VALUE, cityArticleCntOption.optInt(Option.OPTION_VALUE) - 1);
            optionRepository.update(cityStatId, cityArticleCntOption);
        }
        final JSONObject articleCntOption = optionRepository.get(Option.ID_C_STATISTIC_ARTICLE_COUNT);
        articleCntOption.put(Option.OPTION_VALUE, articleCntOption.optInt(Option.OPTION_VALUE) - 1);
        optionRepository.update(Option.ID_C_STATISTIC_ARTICLE_COUNT, articleCntOption);
        articleRepository.remove(articleId);
        // Remove article revisions
        query = new Query().setFilter(CompositeFilterOperator.and(new PropertyFilter(Revision.REVISION_DATA_ID, FilterOperator.EQUAL, articleId), new PropertyFilter(Revision.REVISION_DATA_TYPE, FilterOperator.EQUAL, Revision.DATA_TYPE_C_ARTICLE)));
        final JSONArray articleRevisions = revisionRepository.get(query).optJSONArray(Keys.RESULTS);
        for (int i = 0; i < articleRevisions.length(); i++) {
            final JSONObject articleRevision = articleRevisions.optJSONObject(i);
            revisionRepository.remove(articleRevision.optString(Keys.OBJECT_ID));
        }
        final List<JSONObject> tagArticleRels = tagArticleRepository.getByArticleId(articleId);
        for (final JSONObject tagArticleRel : tagArticleRels) {
            final String tagId = tagArticleRel.optString(Tag.TAG + "_" + Keys.OBJECT_ID);
            final JSONObject tag = tagRepository.get(tagId);
            int cnt = tag.optInt(Tag.TAG_REFERENCE_CNT) - 1;
            cnt = cnt < 0 ? 0 : cnt;
            tag.put(Tag.TAG_REFERENCE_CNT, cnt);
            tag.put(Tag.TAG_RANDOM_DOUBLE, Math.random());
            tagRepository.update(tagId, tag);
        }
        tagArticleRepository.removeByArticleId(articleId);
        notificationRepository.removeByDataId(articleId);
        if (Symphonys.getBoolean("algolia.enabled")) {
            searchMgmtService.removeAlgoliaDocument(article);
        }
        if (Symphonys.getBoolean("es.enabled")) {
            searchMgmtService.removeESDocument(article, Article.ARTICLE);
        }
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Removes an article error [id=" + articleId + "]", e);
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) Transactional(org.b3log.latke.repository.annotation.Transactional)

Example 5 with Transactional

use of org.b3log.latke.repository.annotation.Transactional in project symphony by b3log.

the class BookQueryService method getBookByISBN.

/**
 * Gets a book's information with the specified ISBN.
 *
 * @param isbn the specified ISBN
 * @return book info, returns {@code null} if not found
 */
@Transactional
public JSONObject getBookByISBN(final String isbn) {
    final String url = "https://api.douban.com/v2/book/isbn/" + isbn;
    final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
    final HTTPRequest request = new HTTPRequest();
    request.addHeader(new HTTPHeader(Common.USER_AGENT, Symphonys.USER_AGENT_BOT));
    try {
        request.setURL(new URL(url));
        final HTTPResponse response = urlFetchService.fetch(request);
        final String content = new String(response.getContent(), "UTF-8");
        final JSONObject result = new JSONObject(content);
        if (result.has("code")) {
            return null;
        }
        JSONObject ret = bookRepository.getByISBN(isbn);
        boolean add = false;
        if (null == ret) {
            ret = new JSONObject();
            add = true;
        }
        ret.put(Book.BOOK_ALT_TITLE, result.optString("alt_title"));
        ret.put(Book.BOOK_AUTHOR, result.optJSONArray("author").toString());
        ret.put(Book.BOOK_AUTHOR_INTRO, result.optString("author_intro").replace("\n", "\n\n"));
        ret.put(Book.BOOK_BINDING, result.optString("binding"));
        ret.put(Book.BOOK_CATALOG, result.optString("catalog"));
        final JSONObject series = result.optJSONObject("series");
        if (null != series) {
            ret.put(Book.BOOK_SERIES, series.optString("title"));
        } else {
            ret.put(Book.BOOK_SERIES, "");
        }
        ret.put(Book.BOOK_DOUBAN_URL, result.optString("alt"));
        ret.put(Book.BOOK_IMG_URL, result.optString("image"));
        ret.put(Book.BOOK_ISBN10, result.optString("isbn10"));
        ret.put(Book.BOOK_ISBN13, result.optString("isbn13"));
        ret.put(Book.BOOK_ORIGINAL_TITLE, result.optString("origin_title"));
        ret.put(Book.BOOK_PAGES, result.optString("pages"));
        ret.put(Book.BOOK_PRICE, result.optString("price"));
        ret.put(Book.BOOK_PUBLISH_DATE, result.optString("pubdate"));
        ret.put(Book.BOOK_PUBLISHER, result.optString("publisher"));
        ret.put(Book.BOOK_SUB_TITLE, result.optString("subtitle"));
        ret.put(Book.BOOK_SUMMARY, result.optString("summary").replace("\n", "\n\n"));
        final StringBuilder tagBuilder = new StringBuilder();
        final JSONArray tags = result.optJSONArray("tags");
        for (int i = 0; i < tags.length(); i++) {
            final JSONObject tag = tags.optJSONObject(i);
            tagBuilder.append(tag.optString("name")).append(",");
        }
        if (tagBuilder.length() > 0) {
            tagBuilder.deleteCharAt(tagBuilder.length() - 1);
        }
        ret.put(Book.BOOK_TAGS, tagBuilder.toString());
        ret.put(Book.BOOK_TITLE, result.optString("title"));
        ret.put(Book.BOOK_TRANSLATOR, result.optJSONArray("translator").toString());
        if (add) {
            bookRepository.add(ret);
        } else {
            bookRepository.update(ret.optString(Keys.OBJECT_ID), ret);
        }
        ret.put(Book.BOOK_TRANSLATOR, result.optJSONArray("translator"));
        ret.put(Book.BOOK_AUTHOR, result.optJSONArray("author"));
        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Query book by ISBN [" + isbn + "] failed", e);
        return null;
    }
}
Also used : JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) URL(java.net.URL) ServiceException(org.b3log.latke.service.ServiceException) Transactional(org.b3log.latke.repository.annotation.Transactional)

Aggregations

Transactional (org.b3log.latke.repository.annotation.Transactional)52 ServiceException (org.b3log.latke.service.ServiceException)42 JSONObject (org.json.JSONObject)20 JSONArray (org.json.JSONArray)11 RepositoryException (org.b3log.latke.repository.RepositoryException)6 Query (org.b3log.latke.repository.Query)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URL (java.net.URL)1 ExecutionException (java.util.concurrent.ExecutionException)1 PropertyFilter (org.b3log.latke.repository.PropertyFilter)1 RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)1 TextHTMLRenderer (org.b3log.latke.servlet.renderer.TextHTMLRenderer)1