Search in sources :

Example 41 with ServiceException

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

the class Filler method setArticleExProperties.

/**
     * Sets some extra properties into the specified article with the specified author and preference, performs content
     * and abstract editor processing.
     *
     * <p>
     * Article ext properties:
     * <pre>
     * {
     *     ....,
     *     "authorName": "",
     *     "authorId": "",
     *     "authorThumbnailURL": "",
     *     "hasUpdated": boolean
     * }
     * </pre> </p>
     *
     * @param request the specified HTTP servlet request
     * @param article the specified article
     * @param author the specified author
     * @param preference the specified preference
     * @throws ServiceException service exception
     * @see #setArticlesExProperties(HttpServletRequest, List, JSONObject, JSONObject)
     */
private void setArticleExProperties(final HttpServletRequest request, final JSONObject article, final JSONObject author, final JSONObject preference) throws ServiceException {
    try {
        final String authorName = author.getString(User.USER_NAME);
        article.put(Common.AUTHOR_NAME, authorName);
        final String authorId = author.getString(Keys.OBJECT_ID);
        article.put(Common.AUTHOR_ID, authorId);
        final String userAvatar = author.optString(UserExt.USER_AVATAR);
        if (!Strings.isEmptyOrNull(userAvatar)) {
            article.put(Common.AUTHOR_THUMBNAIL_URL, userAvatar);
        } else {
            final String thumbnailURL = Thumbnails.getGravatarURL(author.optString(User.USER_EMAIL), "128");
            article.put(Common.AUTHOR_THUMBNAIL_URL, thumbnailURL);
        }
        if (preference.getBoolean(Option.ID_C_ENABLE_ARTICLE_UPDATE_HINT)) {
            article.put(Common.HAS_UPDATED, articleQueryService.hasUpdated(article));
        } else {
            article.put(Common.HAS_UPDATED, false);
        }
        if (articleQueryService.needViewPwd(request, article)) {
            final String content = langPropsService.get("articleContentPwd");
            article.put(ARTICLE_CONTENT, content);
        }
        processArticleAbstract(preference, article);
        articleQueryService.markdown(article);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Sets article extra properties failed", e);
        throw new ServiceException(e);
    }
}
Also used : ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) EventException(org.b3log.latke.event.EventException) ServiceException(org.b3log.latke.service.ServiceException)

Example 42 with ServiceException

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

the class InitService method init.

/**
     * Initializes Solo.
     *
     * <p>
     * Initializes the followings in sequence:
     * <ol>
     * <li>Statistic</li>
     * <li>Preference</li>
     * <li>Administrator</li>
     * </ol>
     * </p>
     *
     * <p>
     * We will try to initialize Solo 3 times at most.
     * </p>
     *
     * <p>
     * Posts "Hello World!" article and its comment while Solo initialized.
     * </p>
     *
     * @param requestJSONObject the specified request json object, for example,      <pre>
     * {
     *     "userName": "",
     *     "userEmail": "",
     *     "userPassword": "", // Unhashed
     * }
     * </pre>
     *
     * @throws ServiceException service exception
     */
public void init(final JSONObject requestJSONObject) throws ServiceException {
    if (isInited()) {
        return;
    }
    final RuntimeEnv runtimeEnv = Latkes.getRuntimeEnv();
    if (RuntimeEnv.LOCAL == runtimeEnv) {
        LOGGER.log(Level.INFO, "Solo is running on [" + runtimeEnv + "] environment, database [{0}], creates " + "all tables", Latkes.getRuntimeDatabase());
        if (RuntimeDatabase.H2 == Latkes.getRuntimeDatabase()) {
            String dataDir = Latkes.getLocalProperty("jdbc.URL");
            dataDir = dataDir.replace("~", System.getProperty("user.home"));
            LOGGER.log(Level.INFO, "YOUR DATA will be stored in directory [" + dataDir + "], " + "please pay more attention to it~");
        }
        final List<CreateTableResult> createTableResults = JdbcRepositories.initAllTables();
        for (final CreateTableResult createTableResult : createTableResults) {
            LOGGER.log(Level.DEBUG, "Create table result[tableName={0}, isSuccess={1}]", new Object[] { createTableResult.getName(), createTableResult.isSuccess() });
        }
    }
    int retries = MAX_RETRIES_CNT;
    while (true) {
        final Transaction transaction = userRepository.beginTransaction();
        try {
            final JSONObject statistic = statisticRepository.get(Statistic.STATISTIC);
            if (null == statistic) {
                initStatistic();
                initPreference(requestJSONObject);
                initReplyNotificationTemplate();
                initAdmin(requestJSONObject);
                initLink();
            }
            transaction.commit();
            break;
        } catch (final Exception e) {
            if (0 == retries) {
                LOGGER.log(Level.ERROR, "Initialize Solo error", e);
                throw new ServiceException("Initailize Solo error: " + e.getMessage());
            }
            // Allow retry to occur
            --retries;
            LOGGER.log(Level.WARN, "Retrying to init Solo[retries={0}]", retries);
        } finally {
            if (transaction.isActive()) {
                transaction.rollback();
            }
        }
    }
    final Transaction transaction = userRepository.beginTransaction();
    try {
        helloWorld();
        transaction.commit();
    } catch (final Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        LOGGER.log(Level.ERROR, "Hello World error?!", e);
    }
    try {
        final URLFetchService urlFetchService = URLFetchServiceFactory.getURLFetchService();
        final HTTPRequest req = new HTTPRequest();
        req.setURL(new URL(Latkes.getServePath() + "/blog/symphony/user"));
        urlFetchService.fetch(req);
    } catch (final Exception e) {
        LOGGER.log(Level.TRACE, "Sync account failed");
    }
    pluginManager.load();
}
Also used : HTTPRequest(org.b3log.latke.urlfetch.HTTPRequest) Transaction(org.b3log.latke.repository.Transaction) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) URLFetchService(org.b3log.latke.urlfetch.URLFetchService) RuntimeEnv(org.b3log.latke.RuntimeEnv) CreateTableResult(org.b3log.latke.repository.jdbc.util.JdbcRepositories.CreateTableResult) JSONException(org.json.JSONException) ParseException(java.text.ParseException) ServiceException(org.b3log.latke.service.ServiceException) RepositoryException(org.b3log.latke.repository.RepositoryException) URL(java.net.URL)

Example 43 with ServiceException

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

the class ArticleQueryService method getArticleContent.

/**
     * Gets article contents with the specified article id.
     *
     * <p>
     * Invoking this method dose not effect on article view count.
     * </p>
     *
     * @param request the specified HTTP servlet request
     * @param articleId the specified article id
     * @return article contents, returns {@code null} if not found
     * @throws ServiceException service exception
     */
public String getArticleContent(final HttpServletRequest request, final String articleId) throws ServiceException {
    if (Strings.isEmptyOrNull(articleId)) {
        return null;
    }
    try {
        final JSONObject article = articleRepository.get(articleId);
        if (null == article) {
            return null;
        }
        if (needViewPwd(request, article)) {
            final String content = langPropsService.get("articleContentPwd");
            article.put(ARTICLE_CONTENT, content);
        } else if ("CodeMirror-Markdown".equals(article.optString(ARTICLE_EDITOR_TYPE))) {
            // Markdown to HTML for content and abstract
            Stopwatchs.start("Get Article Content [Markdown]");
            String content = article.optString(ARTICLE_CONTENT);
            content = Emotions.convert(content);
            content = Markdowns.toHTML(content);
            article.put(ARTICLE_CONTENT, content);
            Stopwatchs.end();
        }
        return article.getString(Article.ARTICLE_CONTENT);
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets article content failed[articleId=" + articleId + "]", e);
        throw new ServiceException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException)

Example 44 with ServiceException

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

the class ArticleQueryService method getArticlesByAuthorEmail.

/**
     * Gets <em>published</em> articles by the specified author email, current page number and page size.
     *
     * @param authorEmail the specified author email
     * @param currentPageNum the specified current page number
     * @param pageSize the specified page size
     * @return a list of articles, returns an empty list if not found
     * @throws ServiceException service exception
     */
public List<JSONObject> getArticlesByAuthorEmail(final String authorEmail, final int currentPageNum, final int pageSize) throws ServiceException {
    try {
        final JSONObject result = articleRepository.getByAuthorEmail(authorEmail, currentPageNum, pageSize);
        final JSONArray articles = result.getJSONArray(Keys.RESULTS);
        final List<JSONObject> ret = new ArrayList<JSONObject>();
        for (int i = 0; i < articles.length(); i++) {
            final JSONObject article = articles.getJSONObject(i);
            article.put(ARTICLE_CREATE_TIME, ((Date) article.get(ARTICLE_CREATE_DATE)).getTime());
            ret.add(article);
        }
        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets articles by author email failed[authorEmail=" + authorEmail + ", currentPageNum=" + currentPageNum + ", pageSize=" + pageSize + "]", e);
        throw new ServiceException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException)

Example 45 with ServiceException

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

the class ArticleQueryService method getArticlesByArchiveDate.

/**
     * Gets a list of published articles with the specified archive date id, current page number and page size.
     *
     * @param archiveDateId the specified archive date id
     * @param currentPageNum the specified current page number
     * @param pageSize the specified page size
     * @return a list of articles, returns an empty list if not found
     * @throws ServiceException service exception
     */
public List<JSONObject> getArticlesByArchiveDate(final String archiveDateId, final int currentPageNum, final int pageSize) throws ServiceException {
    try {
        JSONObject result = archiveDateArticleRepository.getByArchiveDateId(archiveDateId, currentPageNum, pageSize);
        final JSONArray relations = result.getJSONArray(Keys.RESULTS);
        if (0 == relations.length()) {
            return Collections.emptyList();
        }
        final Set<String> articleIds = new HashSet<String>();
        for (int i = 0; i < relations.length(); i++) {
            final JSONObject relation = relations.getJSONObject(i);
            final String articleId = relation.getString(Article.ARTICLE + "_" + Keys.OBJECT_ID);
            articleIds.add(articleId);
        }
        final List<JSONObject> ret = new ArrayList<JSONObject>();
        final Query query = new Query().setFilter(new PropertyFilter(Keys.OBJECT_ID, FilterOperator.IN, articleIds)).setPageCount(1).index(Article.ARTICLE_PERMALINK);
        result = articleRepository.get(query);
        final JSONArray articles = result.getJSONArray(Keys.RESULTS);
        for (int i = 0; i < articles.length(); i++) {
            final JSONObject article = articles.getJSONObject(i);
            if (!article.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
                // Skips the unpublished article
                continue;
            }
            article.put(ARTICLE_CREATE_TIME, ((Date) article.get(ARTICLE_CREATE_DATE)).getTime());
            ret.add(article);
        }
        return ret;
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Gets articles by archive date[id=" + archiveDateId + "] failed", e);
        throw new ServiceException(e);
    }
}
Also used : JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) ServiceException(org.b3log.latke.service.ServiceException) JSONException(org.json.JSONException) HashSet(java.util.HashSet)

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