Search in sources :

Example 16 with Template

use of freemarker.template.Template in project solo by b3log.

the class CommentProcessor method addArticleComment.

/**
     * Adds a comment to an article.
     * <p>
     * Renders the response with a json object, for example,
     * <pre>
     * {
     *     "oId": generatedCommentId,
     *     "sc": "COMMENT_ARTICLE_SUCC",
     *     "commentDate": "", // yyyy/MM/dd HH:mm:ss
     *     "commentSharpURL": "",
     *     "commentThumbnailURL": "",
     *     "commentOriginalCommentName": "", // if exists this key, the comment is an reply
     *     "commentContent": "" // HTML
     * }
     * </pre>
     * </p>
     *
     * @param context the specified context, including a request json object, for example,
     *                "captcha": "",
     *                "oId": articleId,
     *                "commentName": "",
     *                "commentEmail": "",
     *                "commentURL": "",
     *                "commentContent": "",
     *                "commentOriginalCommentId": "" // optional, if exists this key, the comment is an reply
     * @throws ServletException servlet exception
     * @throws IOException      io exception
     */
@RequestProcessing(value = "/add-article-comment.do", method = HTTPRequestMethod.POST)
public void addArticleComment(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, Article.ARTICLE);
    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.addArticleComment(requestJSONObject);
        final Map<String, Object> dataModel = new HashMap<>();
        dataModel.put(Comment.COMMENT, addResult);
        final JSONObject article = addResult.optJSONObject(Article.ARTICLE);
        article.put(Common.COMMENTABLE, addResult.opt(Common.COMMENTABLE));
        article.put(Common.PERMALINK, addResult.opt(Common.PERMALINK));
        dataModel.put(Article.ARTICLE, article);
        // 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 article", e);
        jsonObject.put(Keys.STATUS_CODE, false);
        jsonObject.put(Keys.MSG, langPropsService.get("addFailLabel"));
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) JSONObject(org.json.JSONObject) JSONRenderer(org.b3log.latke.servlet.renderer.JSONRenderer) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) HttpServletResponse(javax.servlet.http.HttpServletResponse) JSONObject(org.json.JSONObject) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Template(freemarker.template.Template) RequestProcessing(org.b3log.latke.servlet.annotation.RequestProcessing)

Example 17 with Template

use of freemarker.template.Template in project solo by b3log.

the class TopBars method getTopBarHTML.

/**
     * Generates top bar HTML.
     * 
     * @param request the specified request
     * @param response the specified response
     * @return top bar HTML
     * @throws ServiceException service exception 
     */
public String getTopBarHTML(final HttpServletRequest request, final HttpServletResponse response) throws ServiceException {
    Stopwatchs.start("Gens Top Bar HTML");
    try {
        final Template topBarTemplate = ConsoleRenderer.TEMPLATE_CFG.getTemplate("top-bar.ftl");
        final StringWriter stringWriter = new StringWriter();
        final Map<String, Object> topBarModel = new HashMap<String, Object>();
        userMgmtService.tryLogInWithCookie(request, response);
        final JSONObject currentUser = userQueryService.getCurrentUser(request);
        Keys.fillServer(topBarModel);
        topBarModel.put(Common.IS_LOGGED_IN, false);
        topBarModel.put(Common.IS_MOBILE_REQUEST, Requests.mobileRequest(request));
        topBarModel.put("mobileLabel", langPropsService.get("mobileLabel"));
        topBarModel.put("onlineVisitor1Label", langPropsService.get("onlineVisitor1Label"));
        topBarModel.put(Common.ONLINE_VISITOR_CNT, statisticQueryService.getOnlineVisitorCount());
        if (null == currentUser) {
            topBarModel.put(Common.LOGIN_URL, userService.createLoginURL(Common.ADMIN_INDEX_URI));
            topBarModel.put("loginLabel", langPropsService.get("loginLabel"));
            topBarModel.put("registerLabel", langPropsService.get("registerLabel"));
            topBarTemplate.process(topBarModel, stringWriter);
            return stringWriter.toString();
        }
        topBarModel.put(Common.IS_LOGGED_IN, true);
        topBarModel.put(Common.LOGOUT_URL, userService.createLogoutURL("/"));
        topBarModel.put(Common.IS_ADMIN, Role.ADMIN_ROLE.equals(currentUser.getString(User.USER_ROLE)));
        topBarModel.put(Common.IS_VISITOR, Role.VISITOR_ROLE.equals(currentUser.getString(User.USER_ROLE)));
        topBarModel.put("adminLabel", langPropsService.get("adminLabel"));
        topBarModel.put("logoutLabel", langPropsService.get("logoutLabel"));
        final String userName = currentUser.getString(User.USER_NAME);
        topBarModel.put(User.USER_NAME, userName);
        topBarTemplate.process(topBarModel, stringWriter);
        return stringWriter.toString();
    } catch (final JSONException e) {
        LOGGER.log(Level.ERROR, "Gens top bar HTML failed", e);
        throw new ServiceException(e);
    } catch (final IOException e) {
        LOGGER.log(Level.ERROR, "Gens top bar HTML failed", e);
        throw new ServiceException(e);
    } catch (final TemplateException e) {
        LOGGER.log(Level.ERROR, "Gens top bar HTML failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}
Also used : StringWriter(java.io.StringWriter) JSONObject(org.json.JSONObject) ServiceException(org.b3log.latke.service.ServiceException) HashMap(java.util.HashMap) TemplateException(freemarker.template.TemplateException) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) IOException(java.io.IOException) Template(freemarker.template.Template)

Example 18 with Template

use of freemarker.template.Template in project solo by b3log.

the class Filler method fillSide.

/**
     * Fills side.ftl.
     *
     * @param request the specified HTTP servlet request
     * @param dataModel data model
     * @param preference the specified preference
     * @throws ServiceException service exception
     */
public void fillSide(final HttpServletRequest request, final Map<String, Object> dataModel, final JSONObject preference) throws ServiceException {
    Stopwatchs.start("Fill Side");
    try {
        LOGGER.debug("Filling side....");
        Template template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), "side.ftl");
        if (null == template) {
            LOGGER.debug("The skin dose not contain [side.ftl] template");
            template = Templates.getTemplate((String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME), "index.ftl");
            if (null == template) {
                LOGGER.debug("The skin dose not contain [index.ftl] template");
                return;
            }
        }
        dataModel.put("fillTagArticles", fillTagArticles);
        if (Templates.hasExpression(template, "<#list recentArticles as article>")) {
            fillRecentArticles(dataModel, preference);
        }
        if (Templates.hasExpression(template, "<#list links as link>")) {
            fillLinks(dataModel);
        }
        if (Templates.hasExpression(template, "<#list recentComments as comment>")) {
            fillRecentComments(dataModel, preference);
        }
        if (Templates.hasExpression(template, "<#list mostUsedTags as tag>")) {
            fillMostUsedTags(dataModel, preference);
        }
        if (Templates.hasExpression(template, "<#list mostCommentArticles as article>")) {
            fillMostCommentArticles(dataModel, preference);
        }
        if (Templates.hasExpression(template, "<#list mostViewCountArticles as article>")) {
            fillMostViewCountArticles(dataModel, preference);
        }
        if (Templates.hasExpression(template, "<#list archiveDates as archiveDate>")) {
            fillArchiveDates(dataModel, preference);
        }
    } catch (final ServiceException e) {
        LOGGER.log(Level.ERROR, "Fills side failed", e);
        throw new ServiceException(e);
    } finally {
        Stopwatchs.end();
    }
}
Also used : ServiceException(org.b3log.latke.service.ServiceException) Template(freemarker.template.Template)

Example 19 with Template

use of freemarker.template.Template in project OpenClinica by OpenClinica.

the class EnketoUrlService method populateInstance.

private String populateInstance(CrfVersion crfVersion, FormLayout formLayout, EventCrf eventCrf, String studyOid, String flavor) throws Exception {
    Map<String, Object> data = new HashMap<String, Object>();
    List<ItemGroup> igs = itemGroupDao.findByCrfVersionId(crfVersion.getCrfVersionId());
    for (ItemGroup ig : igs) {
        List<HashMap<String, Object>> hashMapList = new ArrayList<HashMap<String, Object>>();
        List<ItemGroupMetadata> igms = itemGroupMetadataDao.findByItemGroupCrfVersion(ig.getItemGroupId(), crfVersion.getCrfVersionId());
        int maxRowCount = itemDataDao.getMaxCountByEventCrfGroup(eventCrf.getEventCrfId(), ig.getItemGroupId());
        HashMap<String, Object> hashMap = null;
        if (igms.get(0).isRepeatingGroup() && maxRowCount == 0) {
            hashMap = new HashMap<>();
            hashMap.put("index", 1);
            hashMap.put("lastUsedOrdinal", 1);
            for (ItemGroupMetadata igm : igms) {
                hashMap.put(igm.getItem().getName(), "");
                if (flavor.equals(QUERY_FLAVOR))
                    hashMap.put(igm.getItem().getName() + QUERY_SUFFIX, "");
            }
            hashMapList.add(hashMap);
            data.put(ig.getName(), hashMapList);
        }
        boolean rowDeleted = false;
        if (igms.get(0).isRepeatingGroup()) {
            for (int i = 0; i < maxRowCount; i++) {
                rowDeleted = false;
                for (ItemGroupMetadata igm : igms) {
                    ItemData itemData = itemDataDao.findByItemEventCrfOrdinalDeleted(igm.getItem().getItemId(), eventCrf.getEventCrfId(), i + 1);
                    if (itemData != null) {
                        rowDeleted = true;
                        break;
                    }
                }
                if (!rowDeleted) {
                    hashMap = new HashMap<>();
                    hashMap.put("index", i + 1);
                    if (i == 0) {
                        hashMap.put("lastUsedOrdinal", maxRowCount);
                    }
                    for (ItemGroupMetadata igm : igms) {
                        ItemData itemData = itemDataDao.findByItemEventCrfOrdinal(igm.getItem().getItemId(), eventCrf.getEventCrfId(), i + 1);
                        String itemValue = getItemValue(itemData, crfVersion);
                        hashMap.put(igm.getItem().getName(), itemData != null ? itemValue : "");
                        if (flavor.equals(QUERY_FLAVOR)) {
                            if (itemData != null) {
                                ObjectMapper mapper = new ObjectMapper();
                                QueriesBean queriesBean = buildQueryElement(itemData);
                                hashMap.put(igm.getItem().getName() + QUERY_SUFFIX, queriesBean != null ? mapper.writeValueAsString(queriesBean) : "");
                            } else {
                                hashMap.put(igm.getItem().getName() + QUERY_SUFFIX, "");
                            }
                        }
                    }
                    hashMapList.add(hashMap);
                }
            }
        }
        if (igms.get(0).isRepeatingGroup() && maxRowCount != 0) {
            data.put(ig.getName(), hashMapList);
        }
        if (!igms.get(0).isRepeatingGroup()) {
            for (ItemGroupMetadata igm : igms) {
                ItemData itemData = itemDataDao.findByItemEventCrfOrdinal(igm.getItem().getItemId(), eventCrf.getEventCrfId(), 1);
                String itemValue = getItemValue(itemData, crfVersion);
                data.put(igm.getItem().getName(), itemData != null ? itemValue : "");
                if (flavor.equals(QUERY_FLAVOR)) {
                    if (itemData != null) {
                        ObjectMapper mapper = new ObjectMapper();
                        QueriesBean queriesBean = buildQueryElement(itemData);
                        data.put(igm.getItem().getName() + QUERY_SUFFIX, queriesBean != null ? mapper.writeValueAsString(queriesBean) : "");
                    } else {
                        data.put(igm.getItem().getName() + QUERY_SUFFIX, "");
                    }
                }
            }
        }
    }
    String templateStr = null;
    CrfBean crfBean = crfDao.findById(formLayout.getCrf().getCrfId());
    String directoryPath = Utils.getCrfMediaFilePath(crfBean.getOcOid(), formLayout.getOcOid());
    File dir = new File(directoryPath);
    File[] directoryListing = dir.listFiles();
    if (directoryListing != null) {
        for (File child : directoryListing) {
            if (flavor.equals(QUERY_FLAVOR) && child.getName().endsWith(INSTANCE_QUERIES_SUFFIX) || flavor.equals(NO_FLAVOR) && child.getName().endsWith(INSTANCE_SUFFIX)) {
                templateStr = new String(Files.readAllBytes(Paths.get(child.getPath())));
                break;
            }
        }
    }
    Template template = new Template("template name", new StringReader(templateStr), new Configuration());
    StringWriter wtr = new StringWriter();
    template.process(data, wtr);
    String instance = wtr.toString();
    System.out.println(instance);
    return instance;
}
Also used : CrfBean(org.akaza.openclinica.domain.datamap.CrfBean) Configuration(freemarker.template.Configuration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Template(freemarker.template.Template) ItemGroup(org.akaza.openclinica.domain.datamap.ItemGroup) StringWriter(java.io.StringWriter) ItemGroupMetadata(org.akaza.openclinica.domain.datamap.ItemGroupMetadata) QueriesBean(org.akaza.openclinica.core.form.xform.QueriesBean) StringReader(java.io.StringReader) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ItemData(org.akaza.openclinica.domain.datamap.ItemData)

Example 20 with Template

use of freemarker.template.Template in project ORCID-Source by ORCID.

the class TemplateManagerImpl method processTemplate.

@Override
public String processTemplate(String templateName, Map<String, Object> params, Locale locale) {
    try {
        Template template = freeMarkerConfiguration.getTemplate(templateName, locale);
        StringWriter result = new StringWriter();
        template.process(params, result);
        return result.toString();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    } catch (TemplateException e) {
        throw new IllegalArgumentException(e);
    }
}
Also used : StringWriter(java.io.StringWriter) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException) Template(freemarker.template.Template)

Aggregations

Template (freemarker.template.Template)72 IOException (java.io.IOException)33 StringWriter (java.io.StringWriter)32 Configuration (freemarker.template.Configuration)30 Writer (java.io.Writer)26 HashMap (java.util.HashMap)26 TemplateException (freemarker.template.TemplateException)23 OutputStreamWriter (java.io.OutputStreamWriter)13 File (java.io.File)9 Map (java.util.Map)8 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 JSONObject (org.json.JSONObject)6 SimpleHash (freemarker.template.SimpleHash)5 ThirdEyeAnomalyConfiguration (com.linkedin.thirdeye.anomaly.ThirdEyeAnomalyConfiguration)4 StringTemplateLoader (freemarker.cache.StringTemplateLoader)4 Environment (freemarker.core.Environment)4 DefaultObjectWrapper (freemarker.template.DefaultObjectWrapper)4 BufferedWriter (java.io.BufferedWriter)4 FileOutputStream (java.io.FileOutputStream)4 StringReader (java.io.StringReader)4