use of freemarker.template.Template in project gitblit by gitblit.
the class FreemarkerPanel method getMarkupResourceStream.
/**
* @see org.apache.wicket.markup.IMarkupResourceStreamProvider#getMarkupResourceStream(org.apache
* .wicket.MarkupContainer, java.lang.Class)
*/
@Override
public final IResourceStream getMarkupResourceStream(MarkupContainer container, Class<?> containerClass) {
Template template = getTemplate();
if (template == null) {
throw new WicketRuntimeException("could not find Freemarker template for panel: " + this);
}
// evaluate the template and return a new StringResourceStream
StringBuffer sb = new StringBuffer();
sb.append("<wicket:panel>");
sb.append(evaluateFreemarkerTemplate(template));
sb.append("</wicket:panel>");
return new StringResourceStream(sb.toString());
}
use of freemarker.template.Template in project solo by b3log.
the class UserTemplateProcessor method showPage.
/**
* Shows the user template page.
*
* @param context the specified context
* @param request the specified HTTP servlet request
* @param response the specified HTTP servlet response
* @throws IOException io exception
*/
@RequestProcessing(value = "/*.html", method = HTTPRequestMethod.GET)
public void showPage(final HTTPRequestContext context, final HttpServletRequest request, final HttpServletResponse response) throws IOException {
final String requestURI = request.getRequestURI();
String templateName = StringUtils.substringAfterLast(requestURI, "/");
templateName = StringUtils.substringBefore(templateName, ".") + ".ftl";
LOGGER.log(Level.DEBUG, "Shows page[requestURI={0}, templateName={1}]", new Object[] { requestURI, templateName });
final AbstractFreeMarkerRenderer renderer = new FreeMarkerRenderer();
context.setRenderer(renderer);
renderer.setTemplateName(templateName);
final Map<String, Object> dataModel = renderer.getDataModel();
final Template template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), templateName);
if (null == template) {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
} catch (final IOException ex) {
LOGGER.error(ex.getMessage());
}
}
try {
final Map<String, String> langs = langPropsService.getAll(Locales.getLocale(request));
dataModel.putAll(langs);
final JSONObject preference = preferenceQueryService.getPreference();
filler.fillBlogHeader(request, response, dataModel, preference);
filler.fillUserTemplate(request, template, dataModel, preference);
filler.fillBlogFooter(request, dataModel, preference);
Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), dataModel);
statisticMgmtService.incBlogViewCount(request, response);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, e.getMessage(), e);
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (final IOException ex) {
LOGGER.error(ex.getMessage());
}
}
}
use of freemarker.template.Template 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();
}
}
use of freemarker.template.Template in project solo by b3log.
the class CommentProcessor method addPageComment.
/**
* Adds a comment to a page.
* <p>
* Renders the response with a json object, for example,
* <pre>
* {
* "oId": generatedCommentId,
* "sc": "COMMENT_PAGE_SUCC"
* "commentDate": "", // yyyy/MM/dd HH:mm:ss
* "commentSharpURL": "",
* "commentThumbnailURL": "",
* "commentOriginalCommentName": "" // if exists this key, the comment is an reply
* }
* </pre>
* </p>
*
* @param context the specified context, including a request json object, for example,
* "captcha": "",
* "oId": pageId,
* "commentName": "",
* "commentEmail": "",
* "commentURL": "",
* "commentContent": "", // HTML
* "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
* @throws ServletException servlet exception
* @throws IOException io exception
*/
@RequestProcessing(value = "/add-page-comment.do", method = HTTPRequestMethod.POST)
public void addPageComment(final HTTPRequestContext context) throws ServletException, IOException {
final HttpServletRequest httpServletRequest = context.getRequest();
final HttpServletResponse httpServletResponse = context.getResponse();
final JSONObject requestJSONObject = Requests.parseRequestJSONObject(httpServletRequest, httpServletResponse);
requestJSONObject.put(Common.TYPE, Page.PAGE);
fillCommenter(requestJSONObject, httpServletRequest, httpServletResponse);
final JSONObject jsonObject = commentMgmtService.checkAddCommentRequest(requestJSONObject);
final JSONRenderer renderer = new JSONRenderer();
context.setRenderer(renderer);
renderer.setJSONObject(jsonObject);
if (!jsonObject.optBoolean(Keys.STATUS_CODE)) {
LOGGER.log(Level.WARN, "Can't add comment[msg={0}]", jsonObject.optString(Keys.MSG));
return;
}
final HttpSession session = httpServletRequest.getSession(false);
if (null == session) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
final String storedCaptcha = (String) session.getAttribute(CaptchaProcessor.CAPTCHA);
session.removeAttribute(CaptchaProcessor.CAPTCHA);
if (!userQueryService.isLoggedIn(httpServletRequest, httpServletResponse)) {
final String captcha = requestJSONObject.optString(CaptchaProcessor.CAPTCHA);
if (null == storedCaptcha || !storedCaptcha.equals(captcha)) {
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("captchaErrorLabel"));
return;
}
}
try {
final JSONObject addResult = commentMgmtService.addPageComment(requestJSONObject);
final Map<String, Object> dataModel = new HashMap<>();
dataModel.put(Comment.COMMENT, addResult);
final JSONObject page = addResult.optJSONObject(Page.PAGE);
page.put(Common.COMMENTABLE, addResult.opt(Common.COMMENTABLE));
page.put(Common.PERMALINK, addResult.opt(Common.PERMALINK));
dataModel.put(Article.ARTICLE, page);
// https://github.com/b3log/solo/issues/12246
try {
final String skinDirName = (String) httpServletRequest.getAttribute(Keys.TEMAPLTE_DIR_NAME);
final Template template = Templates.MAIN_CFG.getTemplate("common-comment.ftl");
final JSONObject preference = preferenceQueryService.getPreference();
Skins.fillLangs(preference.optString(Option.ID_C_LOCALE_STRING), skinDirName, dataModel);
Keys.fillServer(dataModel);
final StringWriter stringWriter = new StringWriter();
template.process(dataModel, stringWriter);
stringWriter.close();
addResult.put("cmtTpl", stringWriter.toString());
} catch (final Exception e) {
// 1.9.0 向后兼容
}
addResult.put(Keys.STATUS_CODE, true);
renderer.setJSONObject(addResult);
} catch (final Exception e) {
LOGGER.log(Level.ERROR, "Can not add comment on page", e);
jsonObject.put(Keys.STATUS_CODE, false);
jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
}
}
use of freemarker.template.Template in project moco by dreamhead.
the class TemplateResourceReader method readFor.
@Override
public MessageContent readFor(final Optional<? extends Request> request) {
if (!request.isPresent()) {
throw new IllegalStateException("Request is required to render template");
}
MessageContent content = this.template.readFor(request);
try {
Template targetTemplate = createTemplate(content);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(stream);
targetTemplate.process(variables(request.get()), writer);
return content().withContent(stream.toByteArray()).build();
} catch (ParseException e) {
logger.error("Fail to parse template: {}", content.toString());
throw new MocoException(e);
} catch (IOException e) {
throw new MocoException(e);
} catch (TemplateException e) {
throw new MocoException(e);
}
}
Aggregations