Search in sources :

Example 76 with ServiceException

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

the class Filler method fillArchiveDates.

/**
     * Fills archive dates.
     *
     * @param dataModel data model
     * @param preference the specified preference
     * @throws ServiceException service exception
     */
public void fillArchiveDates(final Map<String, Object> dataModel, final JSONObject preference) throws ServiceException {
    Stopwatchs.start("Fill Archive Dates");
    try {
        LOGGER.debug("Filling archive dates....");
        final List<JSONObject> archiveDates = archiveDateRepository.getArchiveDates();
        final List<JSONObject> archiveDates2 = new ArrayList<JSONObject>();
        dataModel.put(ArchiveDate.ARCHIVE_DATES, archiveDates2);
        if (archiveDates.isEmpty()) {
            return;
        }
        archiveDates2.add(archiveDates.get(0));
        if (1 < archiveDates.size()) {
            // XXX: Workaround, remove the duplicated archive dates
            for (int i = 1; i < archiveDates.size(); i++) {
                final JSONObject archiveDate = archiveDates.get(i);
                final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME);
                final String dateString = DateFormatUtils.format(time, "yyyy/MM");
                final JSONObject last = archiveDates2.get(archiveDates2.size() - 1);
                final String lastDateString = DateFormatUtils.format(last.getLong(ArchiveDate.ARCHIVE_TIME), "yyyy/MM");
                if (!dateString.equals(lastDateString)) {
                    archiveDates2.add(archiveDate);
                } else {
                    LOGGER.log(Level.WARN, "Found a duplicated archive date [{0}]", dateString);
                }
            }
        }
        final String localeString = preference.getString(Option.ID_C_LOCALE_STRING);
        final String language = Locales.getLanguage(localeString);
        for (final JSONObject archiveDate : archiveDates2) {
            final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME);
            final String dateString = DateFormatUtils.format(time, "yyyy/MM");
            final String[] dateStrings = dateString.split("/");
            final String year = dateStrings[0];
            final String month = dateStrings[1];
            archiveDate.put(ArchiveDate.ARCHIVE_DATE_YEAR, year);
            archiveDate.put(ArchiveDate.ARCHIVE_DATE_MONTH, month);
            if ("en".equals(language)) {
                final String monthName = Dates.EN_MONTHS.get(month);
                archiveDate.put(Common.MONTH_NAME, monthName);
            }
        }
        dataModel.put(ArchiveDate.ARCHIVE_DATES, archiveDates2);
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, "Fills archive dates failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Fills archive dates failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException)

Example 77 with ServiceException

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

the class Filler method fillLinks.

/**
     * Fills links.
     *
     * @param dataModel data model
     * @throws ServiceException service exception
     */
public void fillLinks(final Map<String, Object> dataModel) throws ServiceException {
    Stopwatchs.start("Fill Links");
    try {
        final Map<String, SortDirection> sorts = new HashMap<String, SortDirection>();
        sorts.put(Link.LINK_ORDER, SortDirection.ASCENDING);
        final Query query = new Query().addSort(Link.LINK_ORDER, SortDirection.ASCENDING).setPageCount(1);
        final JSONObject linkResult = linkRepository.get(query);
        final List<JSONObject> links = org.b3log.latke.util.CollectionUtils.jsonArrayToList(linkResult.getJSONArray(Keys.RESULTS));
        dataModel.put(Link.LINKS, links);
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, "Fills links failed", e);
        throw new ServiceException(e);
    } catch (final RepositoryException e) {
        LOGGER.log(Level.ERROR, "Fills links failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
    Stopwatchs.end();
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) HashMap(java.util.HashMap) JSONException(org.json.JSONException)

Example 78 with ServiceException

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

the class TagProcessor method showTagArticles.

/**
     * Shows articles related with a tag with the specified context.
     *
     * @param context the specified context
     * @throws IOException io exception
     */
@RequestProcessing(value = "/tags/**", method = HTTPRequestMethod.GET)
public void showTagArticles(final HTTPRequestContext context) throws IOException {
    final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
    context.setRenderer(renderer);
    renderer.setTemplateName("tag-articles.ftl");
    final Map<String, Object> dataModel = renderer.getDataModel();
    final HttpServletRequest request = context.getRequest();
    final HttpServletResponse response = context.getResponse();
    try {
        String requestURI = request.getRequestURI();
        if (!requestURI.endsWith("/")) {
            requestURI += "/";
        }
        String tagTitle = getTagTitle(requestURI);
        final int currentPageNum = getCurrentPageNum(requestURI, tagTitle);
        if (-1 == currentPageNum) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        LOGGER.log(Level.DEBUG, "Tag[title={0}, currentPageNum={1}]", new Object[] { tagTitle, currentPageNum });
        tagTitle = URLDecoder.decode(tagTitle, "UTF-8");
        final JSONObject result = tagQueryService.getTagByTitle(tagTitle);
        if (null == result) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        final JSONObject tag = result.getJSONObject(Tag.TAG);
        final String tagId = tag.getString(Keys.OBJECT_ID);
        final JSONObject preference = preferenceQueryService.getPreference();
        Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
        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 List<JSONObject> articles = articleQueryService.getArticlesByTag(tagId, currentPageNum, pageSize);
        if (articles.isEmpty()) {
            try {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (final IOException ex) {
                LOGGER.error(ex.getMessage());
            }
        }
        final boolean hasMultipleUsers = userQueryService.hasMultipleUsers();
        if (hasMultipleUsers) {
            filler.setArticlesExProperties(request, articles, preference);
        } else {
            // All articles composed by the same author
            final JSONObject author = articleQueryService.getAuthor(articles.get(0));
            filler.setArticlesExProperties(request, articles, author, preference);
        }
        final int tagArticleCount = tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT);
        final int pageCount = (int) Math.ceil((double) tagArticleCount / (double) pageSize);
        LOGGER.log(Level.TRACE, "Paginate tag-articles[currentPageNum={0}, pageSize={1}, pageCount={2}, windowSize={3}]", new Object[] { currentPageNum, pageSize, pageCount, windowSize });
        final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize);
        LOGGER.log(Level.TRACE, "tag-articles[pageNums={0}]", pageNums);
        Collections.sort(articles, Comparators.ARTICLE_CREATE_DATE_COMPARATOR);
        fillPagination(dataModel, pageCount, currentPageNum, articles, pageNums);
        dataModel.put(Common.PATH, "/tags/" + URLEncoder.encode(tagTitle, "UTF-8"));
        dataModel.put(Keys.OBJECT_ID, tagId);
        dataModel.put(Tag.TAG, tag);
        filler.fillSide(request, dataModel, preference);
        filler.fillBlogHeader(request, response, dataModel, preference);
        filler.fillBlogFooter(request, dataModel, preference);
        statisticMgmtService.incBlogViewCount(request, response);
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, e.getMessage(), e);
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } catch (final IOException ex) {
            LOGGER.error(ex.getMessage());
        }
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONException(org.json.JSONException) FreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.FreeMarkerRenderer) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) IOException(java.io.IOException) AbstractFreeMarkerRenderer(org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer) HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONObject(org.json.JSONObject) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 79 with ServiceException

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

the class PageConsole method addPage.

/**
     * Adds a page with the specified request.
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "oId": "", // Generated page id
     *     "msg": ""
     * }
     * </pre>
     * </p>
     * 
     * @param context the specified http request context
     * @param request the specified http servlet request, for example,
     * <pre>
     * {
     *     "page": {
     *         "pageTitle": "",
     *         "pageContent": "",
     *         "pagePermalink": "" // optional,
     *         "pageCommentable": boolean,
     *         "pageType": "",
     *         "pageOpenTarget": ""
     *     }
     * }, see {@link org.b3log.solo.model.Page} for more details
     * </pre>
     * @param response the specified http servlet response
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/page/", method = HTTPRequestMethod.POST)
public void addPage(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    if (!userQueryService.isAdminLoggedIn(request)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final JSONRenderer renderer = new JSONRenderer();
    context.setRenderer(renderer);
    final JSONObject ret = new JSONObject();
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        final String pageId = pageMgmtService.addPage(requestJSONObject);
        ret.put(Keys.OBJECT_ID, pageId);
        ret.put(Keys.MSG, langPropsService.get("addSuccLabel"));
        ret.put(Keys.STATUS_CODE, true);
        renderer.setJSONObject(ret);
    } catch (final ServiceException e) {
        // May be permalink check exception
        LOGGER.log(Level.WARN, 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 80 with ServiceException

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

the class PageConsole method updatePage.

/**
     * Updates a page by the specified request.
     * 
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "sc": boolean,
     *     "msg": ""
     * }
     * </pre>
     * </p>
     *
     * @param request the specified http servlet request, for example,
     * <pre>
     * {
     *     "page": {
     *         "oId": "",
     *         "pageTitle": "",
     *         "pageContent": "",
     *         "pageOrder": int,
     *         "pageCommentCount": int,
     *         "pagePermalink": "",
     *         "pageCommentable": boolean,
     *         "pageType": "",
     *         "pageOpenTarget": ""
     *     }
     * }, see {@link org.b3log.solo.model.Page} for more details
     * </pre>
     * @param response the specified http servlet response
     * @param context the specified http request context
     * @throws Exception exception
     */
@RequestProcessing(value = "/console/page/", method = HTTPRequestMethod.PUT)
public void updatePage(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);
    final JSONObject ret = new JSONObject();
    try {
        final JSONObject requestJSONObject = Requests.parseRequestJSONObject(request, response);
        pageMgmtService.updatePage(requestJSONObject);
        ret.put(Keys.STATUS_CODE, true);
        ret.put(Keys.MSG, langPropsService.get("updateSuccLabel"));
        renderer.setJSONObject(ret);
    } 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)

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