/**
   * Update Preference.
   *
   * @throws Exception exception
   */
  @Test(dependsOnMethods = "init")
  public void updatePreference() throws Exception {
    final PreferenceMgmtService preferenceMgmtService = getPreferenceMgmtService();
    final PreferenceQueryService preferenceQueryService = getPreferenceQueryService();
    JSONObject preference = preferenceQueryService.getPreference();

    Assert.assertEquals(
        preference.getString(Preference.BLOG_TITLE), Preference.Default.DEFAULT_BLOG_TITLE);

    preference.put(Preference.BLOG_TITLE, "updated blog title");
    preferenceMgmtService.updatePreference(preference);

    preference = preferenceQueryService.getPreference();
    Assert.assertEquals(preference.getString(Preference.BLOG_TITLE), "updated blog title");
  }
  /**
   * Render a page template with the destination URL.
   *
   * @param context the context
   * @param pageTemplate the page template
   * @param destinationURL the destination URL
   * @param request for reset password page
   * @throws JSONException the JSONException
   * @throws ServiceException the ServiceException
   */
  private void renderPage(
      final HTTPRequestContext context,
      final String pageTemplate,
      final String destinationURL,
      final HttpServletRequest request)
      throws JSONException, ServiceException {
    final AbstractFreeMarkerRenderer renderer = new ConsoleRenderer();

    renderer.setTemplateName(pageTemplate);
    context.setRenderer(renderer);

    final Map<String, Object> dataModel = renderer.getDataModel();
    final Map<String, String> langs = langPropsService.getAll(Latkes.getLocale());
    final JSONObject preference = preferenceQueryService.getPreference();

    dataModel.putAll(langs);
    dataModel.put(Common.GOTO, destinationURL);
    dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
    dataModel.put(Common.VERSION, SoloServletListener.VERSION);
    dataModel.put(Common.STATIC_RESOURCE_VERSION, Latkes.getStaticResourceVersion());
    dataModel.put(Preference.BLOG_TITLE, preference.getString(Preference.BLOG_TITLE));

    final String token = request.getParameter("token");
    final String email = request.getParameter("login");
    final JSONObject tokenObj = optionQueryService.getOptionById(token);

    if (tokenObj == null) {
      dataModel.put("inputType", "email");
    } else {
      // TODO verify the expired time in the tokenObj
      dataModel.put("inputType", "password");
      dataModel.put("userEmailHidden", email);
    }

    final String from = request.getParameter("from");

    if ("forgot".equals(from)) {
      dataModel.put("resetMsg", langPropsService.get("resetPwdSuccessSend"));
    } else if ("reset".equals(from)) {
      dataModel.put("resetMsg", langPropsService.get("resetPwdSuccessMsg"));
    } else {
      dataModel.put("resetMsg", "");
    }

    Keys.fillRuntime(dataModel);
    filler.fillMinified(dataModel);
  }
  /**
   * Sends the password resetting URL with a random token.
   *
   * @param userEmail the given email
   * @param jsonObject return code and message object
   * @throws JSONException the JSONException
   * @throws ServiceException the ServiceException
   * @throws IOException the IOException
   * @throws RepositoryException the RepositoryException
   */
  private void sendResetUrl(final String userEmail, final JSONObject jsonObject)
      throws JSONException, ServiceException, IOException, RepositoryException {
    final JSONObject preference = preferenceQueryService.getPreference();
    final String token = new Randoms().nextStringWithMD5();
    final String adminEmail = preference.getString(Preference.ADMIN_EMAIL);
    final String mailSubject = langPropsService.get("resetPwdMailSubject");
    final String mailBody =
        langPropsService.get("resetPwdMailBody")
            + " "
            + Latkes.getServePath()
            + "/forgot?token="
            + token
            + "&login="******"passwordReset");
    option.put(Option.OPTION_VALUE, System.currentTimeMillis());

    final Transaction transaction = optionRepository.beginTransaction();

    optionRepository.add(option);
    transaction.commit();

    message.setFrom(adminEmail);
    message.addRecipient(userEmail);
    message.setSubject(mailSubject);
    message.setHtmlBody(mailBody);

    mailService.send(message);

    jsonObject.put("succeed", true);
    jsonObject.put("to", Latkes.getServePath() + "/login?from=forgot");
    jsonObject.put(Keys.MSG, langPropsService.get("resetPwdSuccessSend"));

    LOGGER.log(
        Level.DEBUG,
        "Sent a mail[mailSubject={0}, mailBody=[{1}] to [{2}]",
        new Object[] {mailSubject, mailBody, userEmail});
  }
Exemple #4
0
  @Override
  public void action(final Event<JSONObject> event) throws EventException {
    final JSONObject data = event.getData();

    LOGGER.log(
        Level.DEBUG,
        "Processing an event[type={0}, data={1}] in listener[className={2}]",
        new Object[] {event.getType(), data, ArticleSender.class.getName()});
    try {
      final JSONObject originalArticle = data.getJSONObject(Article.ARTICLE);

      if (!originalArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
        LOGGER.log(
            Level.DEBUG,
            "Ignores post article[title={0}] to Rhythm",
            originalArticle.getString(Article.ARTICLE_TITLE));

        return;
      }

      final LatkeBeanManager beanManager = Lifecycle.getBeanManager();
      final PreferenceQueryService preferenceQueryService =
          beanManager.getReference(PreferenceQueryService.class);

      final JSONObject preference = preferenceQueryService.getPreference();

      if (null == preference) {
        throw new EventException("Not found preference");
      }

      if (!Strings.isEmptyOrNull(originalArticle.optString(Article.ARTICLE_VIEW_PWD))) {
        return;
      }

      if (Latkes.getServePath().contains("localhost")) {
        LOGGER.log(
            Level.INFO,
            "Solo runs on local server, so should not send this article[id={0}, title={1}] to Rhythm",
            new Object[] {
              originalArticle.getString(Keys.OBJECT_ID),
              originalArticle.getString(Article.ARTICLE_TITLE)
            });
        return;
      }

      final HTTPRequest httpRequest = new HTTPRequest();

      httpRequest.setURL(ADD_ARTICLE_URL);
      httpRequest.setRequestMethod(HTTPRequestMethod.POST);
      final JSONObject requestJSONObject = new JSONObject();
      final JSONObject article = new JSONObject();

      article.put(Keys.OBJECT_ID, originalArticle.getString(Keys.OBJECT_ID));
      article.put(Article.ARTICLE_TITLE, originalArticle.getString(Article.ARTICLE_TITLE));
      article.put(Article.ARTICLE_PERMALINK, originalArticle.getString(Article.ARTICLE_PERMALINK));
      article.put(Article.ARTICLE_TAGS_REF, originalArticle.getString(Article.ARTICLE_TAGS_REF));
      article.put(
          Article.ARTICLE_AUTHOR_EMAIL, originalArticle.getString(Article.ARTICLE_AUTHOR_EMAIL));
      article.put(Article.ARTICLE_CONTENT, originalArticle.getString(Article.ARTICLE_CONTENT));
      article.put(
          Article.ARTICLE_CREATE_DATE,
          ((Date) originalArticle.get(Article.ARTICLE_CREATE_DATE)).getTime());
      article.put(Common.POST_TO_COMMUNITY, originalArticle.getBoolean(Common.POST_TO_COMMUNITY));

      // Removes this property avoid to persist
      originalArticle.remove(Common.POST_TO_COMMUNITY);

      requestJSONObject.put(Article.ARTICLE, article);
      requestJSONObject.put(Common.BLOG_VERSION, SoloServletListener.VERSION);
      requestJSONObject.put(Common.BLOG, "B3log Solo");
      requestJSONObject.put(Option.ID_C_BLOG_TITLE, preference.getString(Option.ID_C_BLOG_TITLE));
      requestJSONObject.put("blogHost", Latkes.getServePath());
      requestJSONObject.put("userB3Key", preference.optString(Option.ID_C_KEY_OF_SOLO));
      requestJSONObject.put("clientAdminEmail", preference.optString(Option.ID_C_ADMIN_EMAIL));
      requestJSONObject.put("clientRuntimeEnv", Latkes.getRuntimeEnv().name());

      httpRequest.setPayload(requestJSONObject.toString().getBytes("UTF-8"));

      urlFetchService.fetchAsync(httpRequest);
    } catch (final Exception e) {
      LOGGER.log(Level.ERROR, "Sends an article to Rhythm error: {0}", e.getMessage());
    }

    LOGGER.log(Level.DEBUG, "Sent an article to Rhythm");
  }
Exemple #5
0
  /**
   * 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());
      }
    }
  }