Search in sources :

Example 81 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class PreferenceConsole method updateQiniu.

/**
     * Updates the Qiniu preference by the specified request.
     *
     * @param request the specified http servlet request, for example,      <pre>
     * {
     *     "qiniuAccessKey": "",
     *     "qiniuSecretKey": "",
     *     "qiniuDomain": "",
     *     "qiniuBucket": ""
     * }, see {@link org.b3log.solo.model.Option} for more details
     * </pre>
     *
     * @param response the specified http servlet response
     * @param context the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = PREFERENCE_URI_PREFIX + "qiniu", method = HTTPRequestMethod.PUT)
public void updateQiniu(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    if (!userQueryService.isAdminLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final String accessKey = requestJSONObject.optString(Option.ID_C_QINIU_ACCESS_KEY).trim();
        final String secretKey = requestJSONObject.optString(Option.ID_C_QINIU_SECRET_KEY).trim();
        String domain = requestJSONObject.optString(Option.ID_C_QINIU_DOMAIN).trim();
        final String bucket = requestJSONObject.optString(Option.ID_C_QINIU_BUCKET).trim();
        final JSONObject ret = new JSONObject();
        renderer.setJSONObject(ret);
        if (StringUtils.isNotBlank(domain) && !StringUtils.endsWith(domain, "/")) {
            domain += "/";
        }
        final JSONObject accessKeyOpt = new JSONObject();
        accessKeyOpt.put(Keys.OBJECT_ID, Option.ID_C_QINIU_ACCESS_KEY);
        accessKeyOpt.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_QINIU);
        accessKeyOpt.put(Option.OPTION_VALUE, accessKey);
        final JSONObject secretKeyOpt = new JSONObject();
        secretKeyOpt.put(Keys.OBJECT_ID, Option.ID_C_QINIU_SECRET_KEY);
        secretKeyOpt.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_QINIU);
        secretKeyOpt.put(Option.OPTION_VALUE, secretKey);
        final JSONObject domainOpt = new JSONObject();
        domainOpt.put(Keys.OBJECT_ID, Option.ID_C_QINIU_DOMAIN);
        domainOpt.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_QINIU);
        domainOpt.put(Option.OPTION_VALUE, domain);
        final JSONObject bucketOpt = new JSONObject();
        bucketOpt.put(Keys.OBJECT_ID, Option.ID_C_QINIU_BUCKET);
        bucketOpt.put(Option.OPTION_CATEGORY, Option.CATEGORY_C_QINIU);
        bucketOpt.put(Option.OPTION_VALUE, bucket);
        optionMgmtService.addOrUpdateOption(accessKeyOpt);
        optionMgmtService.addOrUpdateOption(secretKeyOpt);
        optionMgmtService.addOrUpdateOption(domainOpt);
        optionMgmtService.addOrUpdateOption(bucketOpt);
        ret.put(Keys.STATUS_CODE, true);
        ret.put(Keys.MSG, langPropsService.get("updateSuccLabel"));
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, e.getMessage());
    }
}
Also used : JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 82 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class PreferenceConsole method updatePreference.

/**
     * Updates the preference by the specified request.
     *
     * @param request the specified http servlet request, for example,      <pre>
     * {
     *     "preference": {
     *         "mostViewArticleDisplayCount": int,
     *         "recentCommentDisplayCount": int,
     *         "mostUsedTagDisplayCount": int,
     *         "articleListDisplayCount": int,
     *         "articleListPaginationWindowSize": int,
     *         "mostCommentArticleDisplayCount": int,
     *         "externalRelevantArticlesDisplayCount": int,
     *         "relevantArticlesDisplayCount": int,
     *         "randomArticlesDisplayCount": int,
     *         "blogTitle": "",
     *         "blogSubtitle": "",
     *         "skinDirName": "",
     *         "localeString": "",
     *         "timeZoneId": "",
     *         "noticeBoard": "",
     *         "footerContent": "",
     *         "htmlHead": "",
     *         "metaKeywords": "",
     *         "metaDescription": "",
     *         "enableArticleUpdateHint": boolean,
     *         "signs": [{
     *             "oId": "",
     *             "signHTML": ""
     *         }, ...],
     *         "allowVisitDraftViaPermalink": boolean,
     *         "allowRegister": boolean,
     *         "articleListStyle": "",
     *         "commentable": boolean,
     *         "feedOutputMode: "",
     *         "feedOutputCnt": int
     *     }
     * }, see {@link org.b3log.solo.model.Preference} for more details
     * </pre>
     *
     * @param response the specified http servlet response
     * @param context the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = PREFERENCE_URI_PREFIX, method = HTTPRequestMethod.PUT)
public void updatePreference(final HttpServletRequest request, final HttpServletResponse response, final HTTPRequestContext context) throws Exception {
    if (!userQueryService.isAdminLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final JSONObject preference = requestJSONObject.getJSONObject(Option.CATEGORY_C_PREFERENCE);
        final JSONObject ret = new JSONObject();
        renderer.setJSONObject(ret);
        if (isInvalid(preference, ret)) {
            return;
        }
        preferenceMgmtService.updatePreference(preference);
        final Cookie cookie = new Cookie(Skin.SKIN, preference.getString(Skin.SKIN_DIR_NAME));
        cookie.setPath("/");
        response.addCookie(cookie);
        ret.put(Keys.STATUS_CODE, true);
        ret.put(Keys.MSG, langPropsService.get("updateSuccLabel"));
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        final JSONObject jsonObject = QueryResults.defaultResult();
        renderer.setJSONObject(jsonObject);
        jsonObject.put(Keys.MSG, e.getMessage());
    }
}
Also used : Cookie(javax.servlet.http.Cookie) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 83 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class Filler method fillTags.

/**
     * Fills tags.
     *
     * @param dataModel data model
     * @throws ServiceException service exception
     */
public void fillTags(final Map<String, Object> dataModel) throws ServiceException {
    Stopwatchs.start("Fill Tags");
    try {
        final List<JSONObject> tags = tagQueryService.getTags();
        tagQueryService.removeForUnpublishedArticles(tags);
        Collections.sort(tags, Comparators.TAG_REF_CNT_COMPARATOR);
        dataModel.put(Tag.TAGS, tags);
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, "Fills tags failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Fills tagss failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
    Stopwatchs.end();
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException)

Example 84 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class Filler method fillMostUsedTags.

/**
     * Fills most used tags.
     *
     * @param dataModel data model
     * @param preference the specified preference
     * @throws ServiceException service exception
     */
public void fillMostUsedTags(final Map<String, Object> dataModel, final JSONObject preference) throws ServiceException {
    Stopwatchs.start("Fill Most Used Tags");
    try {
        LOGGER.debug("Filling most used tags....");
        final int mostUsedTagDisplayCnt = preference.getInt(Option.ID_C_MOST_USED_TAG_DISPLAY_CNT);
        final List<JSONObject> tags = tagRepository.getMostUsedTags(mostUsedTagDisplayCnt);
        tagQueryService.removeForUnpublishedArticles(tags);
        dataModel.put(Common.MOST_USED_TAGS, tags);
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, "Fills most used tags failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Fills most used tags failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException)

Example 85 with ServiceException

use of org.b3log.latke.service.ServiceException in project solo by b3log.

the class Filler method fillIndexArticles.

/**
     * Fills articles in index.ftl.
     *
     * @param request the specified HTTP servlet request
     * @param dataModel data model
     * @param currentPageNum current page number
     * @param preference the specified preference
     * @throws ServiceException service exception
     */
public void fillIndexArticles(final HttpServletRequest request, final Map<String, Object> dataModel, final int currentPageNum, final JSONObject preference) throws ServiceException {
    Stopwatchs.start("Fill Index Articles");
    try {
        final int pageSize = preference.getInt(Option.ID_C_ARTICLE_LIST_DISPLAY_COUNT);
        final int windowSize = preference.getInt(Option.ID_C_ARTICLE_LIST_PAGINATION_WINDOW_SIZE);
        final JSONObject statistic = statisticQueryService.getStatistic();
        final int publishedArticleCnt = statistic.getInt(Statistic.STATISTIC_PUBLISHED_ARTICLE_COUNT);
        final int pageCount = (int) Math.ceil((double) publishedArticleCnt / (double) pageSize);
        final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize).setPageCount(pageCount).setFilter(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, PUBLISHED));
        final Template template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), "index.ftl");
        boolean isArticles1 = false;
        if (null == template) {
            LOGGER.debug("The skin dose not contain [index.ftl] template");
        } else // See https://github.com/b3log/solo/issues/179 for more details
        if (Templates.hasExpression(template, "<#list articles1 as article>")) {
            isArticles1 = true;
            query.addSort(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING);
            LOGGER.trace("Query ${articles1} in index.ftl");
        } else {
            // <#list articles as article>
            query.addSort(Article.ARTICLE_PUT_TOP, SortDirection.DESCENDING);
            if (preference.getBoolean(Option.ID_C_ENABLE_ARTICLE_UPDATE_HINT)) {
                query.addSort(Article.ARTICLE_UPDATE_DATE, SortDirection.DESCENDING);
            } else {
                query.addSort(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING);
            }
        }
        query.index(Article.ARTICLE_PERMALINK);
        final JSONObject result = articleRepository.get(query);
        final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
        if (0 != pageNums.size()) {
            dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0));
            dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1));
        }
        dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount);
        dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums);
        final List<JSONObject> articles = org.b3log.latke.util.CollectionUtils.jsonArrayToList(result.getJSONArray(Keys.RESULTS));
        final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
        if (hasMultipleUsers) {
            setArticlesExProperties(request, articles, preference);
        } else if (!articles.isEmpty()) {
            final JSONObject author = articleQueryService.getAuthor(articles.get(0));
            setArticlesExProperties(request, articles, author, preference);
        }
        if (!isArticles1) {
            dataModel.put(Article.ARTICLES, articles);
        } else {
            dataModel.put(Article.ARTICLES + "1", articles);
        }
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, "Fills index articles failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Fills index articles failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) Template(freemarker.template.Template)

Aggregations

ServiceException (org.b3log.latke.service.ServiceException)102 JSONObject (org.json.JSONObject)91 JSONException (org.json.JSONException)45 RepositoryException (org.b3log.latke.repository.RepositoryException)34 Transaction (org.b3log.latke.repository.Transaction)31 RequestProcessing (org.b3log.latke.servlet.annotation.RequestProcessing)23 JSONArray (org.json.JSONArray)17 JSONRenderer (org.b3log.latke.servlet.renderer.JSONRenderer)16 EventException (org.b3log.latke.event.EventException)14 IOException (java.io.IOException)11 ParseException (java.text.ParseException)10 ArrayList (java.util.ArrayList)8 Query (org.b3log.latke.repository.Query)8 Date (java.util.Date)7 AbstractFreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer)6 Template (freemarker.template.Template)3 FreeMarkerRenderer (org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer)3 ArchiveDate (org.b3log.solo.model.ArchiveDate)3 URL (java.net.URL)2 HashMap (java.util.HashMap)2