Search in sources :

Example 26 with Context

use of org.apache.velocity.context.Context in project OpenOLAT by OpenOLAT.

the class AssessmentObjectComponentRenderer method renderCustomInteraction.

/**
 * Render the interaction or the PositionStageObject
 * @param renderer
 * @param sb
 * @param interaction
 * @param assessmentItem
 * @param itemSessionState
 * @param component
 * @param ubu
 * @param translator
 */
private void renderCustomInteraction(AssessmentRenderer renderer, StringOutput sb, CustomInteraction<?> interaction, ResolvedAssessmentItem resolvedAssessmentItem, ItemSessionState itemSessionState, AssessmentObjectComponent component, URLBuilder ubu, Translator translator) {
    Context ctx = new VelocityContext();
    ctx.put("interaction", interaction);
    String page;
    if (interaction instanceof MathEntryInteraction) {
        page = velocity_root.concat("/mathEntryInteraction.html");
    } else {
        page = velocity_root.concat("/unsupportedCustomInteraction.html");
    }
    renderVelocity(renderer, sb, interaction, ctx, page, resolvedAssessmentItem, itemSessionState, component, ubu, translator);
}
Also used : Context(org.apache.velocity.context.Context) VelocityContext(org.apache.velocity.VelocityContext) VelocityContext(org.apache.velocity.VelocityContext) AssessmentRenderFunctions.contentAsString(org.olat.ims.qti21.ui.components.AssessmentRenderFunctions.contentAsString) MathEntryInteraction(uk.ac.ed.ph.qtiworks.mathassess.MathEntryInteraction)

Example 27 with Context

use of org.apache.velocity.context.Context in project OpenOLAT by OpenOLAT.

the class DropboxController method getConfirmation.

private String getConfirmation(UserRequest ureq, String filename) {
    // grab confirmation-text from bb-config
    String confirmation = config.getStringValue(TACourseNode.CONF_DROPBOX_CONFIRMATION);
    Context c = new VelocityContext();
    Identity identity = ureq.getIdentity();
    c.put("login", identity.getName());
    c.put("first", identity.getUser().getProperty(UserConstants.FIRSTNAME, getLocale()));
    c.put("last", identity.getUser().getProperty(UserConstants.LASTNAME, getLocale()));
    c.put("email", UserManager.getInstance().getUserDisplayEmail(identity, getLocale()));
    c.put("filename", filename);
    Date now = new Date();
    Formatter f = Formatter.getInstance(ureq.getLocale());
    c.put("date", f.formatDate(now));
    c.put("time", f.formatTime(now));
    // update attempts counter for this user: one file - one attempts
    AssessableCourseNode acn = (AssessableCourseNode) node;
    acn.incrementUserAttempts(userCourseEnv, Role.user);
    // log entry for this file
    UserNodeAuditManager am = userCourseEnv.getCourseEnvironment().getAuditManager();
    am.appendToUserNodeLog(node, identity, identity, "FILE UPLOADED: " + filename);
    return VelocityHelper.getInstance().evaluateVTL(confirmation, c);
}
Also used : Context(org.apache.velocity.context.Context) SubscriptionContext(org.olat.core.commons.services.notifications.SubscriptionContext) VelocityContext(org.apache.velocity.VelocityContext) MailContext(org.olat.core.util.mail.MailContext) AssessableCourseNode(org.olat.course.nodes.AssessableCourseNode) UserNodeAuditManager(org.olat.course.auditing.UserNodeAuditManager) VelocityContext(org.apache.velocity.VelocityContext) Formatter(org.olat.core.util.Formatter) Identity(org.olat.core.id.Identity) Date(java.util.Date)

Example 28 with Context

use of org.apache.velocity.context.Context in project entando-core by entando.

the class BaseContentRenderer method render.

@Override
public String render(Content content, long modelId, String langCode, RequestContext reqCtx) {
    String renderedEntity = null;
    List<TextAttributeCharReplaceInfo> conversions = null;
    try {
        conversions = this.convertSpecialCharacters(content, langCode);
        String contentModel = this.getModelShape(modelId);
        Context velocityContext = new VelocityContext();
        ContentWrapper contentWrapper = (ContentWrapper) this.getEntityWrapper(content);
        contentWrapper.setRenderingLang(langCode);
        contentWrapper.setReqCtx(reqCtx);
        velocityContext.put(this.getEntityWrapperContextName(), contentWrapper);
        I18nManagerWrapper i18nWrapper = new I18nManagerWrapper(langCode, this.getI18nManager());
        velocityContext.put("i18n", i18nWrapper);
        SystemInfoWrapper systemInfoWrapper = new SystemInfoWrapper(reqCtx);
        velocityContext.put("info", systemInfoWrapper);
        StringWriter stringWriter = new StringWriter();
        boolean isEvaluated = Velocity.evaluate(velocityContext, stringWriter, "render", contentModel);
        if (!isEvaluated) {
            throw new ApsSystemException("Error rendering content");
        }
        stringWriter.flush();
        renderedEntity = stringWriter.toString();
    } catch (Throwable t) {
        _logger.error("Error rendering content", t);
        // ApsSystemUtils.logThrowable(t, this, "render", "Error rendering content");
        renderedEntity = "";
    } finally {
        if (null != conversions) {
            this.replaceSpecialCharacters(conversions);
        }
    }
    return renderedEntity;
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) RequestContext(com.agiletec.aps.system.RequestContext) Context(org.apache.velocity.context.Context) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) TextAttributeCharReplaceInfo(com.agiletec.aps.system.common.renderer.TextAttributeCharReplaceInfo) ApsSystemException(com.agiletec.aps.system.exception.ApsSystemException) I18nManagerWrapper(com.agiletec.aps.system.services.i18n.I18nManagerWrapper)

Example 29 with Context

use of org.apache.velocity.context.Context in project openolat by klemens.

the class EmailProperty method addFormItem.

/**
 * @see org.olat.user.propertyhandlers.UserPropertyHandler#addFormItem(java.util.Locale, org.olat.core.id.User, java.lang.String, boolean, org.olat.core.gui.components.form.flexible.FormItemContainer)
 */
@Override
public FormItem addFormItem(Locale locale, final User user, String usageIdentifyer, final boolean isAdministrativeUser, FormItemContainer formItemContainer) {
    org.olat.core.gui.components.form.flexible.elements.TextElement tElem = null;
    tElem = (org.olat.core.gui.components.form.flexible.elements.TextElement) super.addFormItem(locale, user, usageIdentifyer, isAdministrativeUser, formItemContainer);
    // to validate the input a special isValidValue is used.
    if (usageIdentifyer.equals(UserBulkChangeStep00.class.getCanonicalName())) {
        tElem.setItemValidatorProvider(new ItemValidatorProvider() {

            @Override
            public boolean isValidValue(String value, ValidationError validationError, Locale locale2) {
                UserBulkChangeManager ubcMan = CoreSpringFactory.getImpl(UserBulkChangeManager.class);
                Context vcContext = new VelocityContext();
                if (user == null) {
                    vcContext = ubcMan.getDemoContext(locale2);
                } else // should be used if user-argument !=null --> move to right place
                {
                    Long userKey = user.getKey();
                    Identity identity = BaseSecurityManager.getInstance().loadIdentityByKey(userKey);
                    ubcMan.setUserContext(identity, vcContext);
                }
                value = value.replace("$", "$!");
                String evaluatedValue = ubcMan.evaluateValueWithUserContext(value, vcContext);
                return EmailProperty.this.isValidValue(user, evaluatedValue, validationError, locale2);
            }
        });
    }
    return tElem;
}
Also used : Locale(java.util.Locale) VelocityContext(org.apache.velocity.VelocityContext) Context(org.apache.velocity.context.Context) ItemValidatorProvider(org.olat.core.gui.components.form.flexible.impl.elements.ItemValidatorProvider) VelocityContext(org.apache.velocity.VelocityContext) UserBulkChangeStep00(org.olat.admin.user.bulkChange.UserBulkChangeStep00) UserBulkChangeManager(org.olat.admin.user.bulkChange.UserBulkChangeManager) ValidationError(org.olat.core.gui.components.form.ValidationError) Identity(org.olat.core.id.Identity)

Example 30 with Context

use of org.apache.velocity.context.Context in project nimbus by nimbus-org.

the class VelocityTemplateEngineService method transform.

/**
 * テンプレートファイルとデータファイルを読み込んで、変換を行い出力ファイルに書き出す。<p>
 * テンプレートファイルは、Apache VelocityのVTL(Velocity Template Language)で記述する。<br>
 * データファイルは、VTLで参照するオブジェクトを、2種類の記述方法を混在させて、複数記述できる。<br>
 * 1つは、プロパティ形式で、"変数名=値"で指定する。複数指定する場合は、改行して記述する。<br>
 * もう1つは、CSV形式で、1行目に変数名、2行目にプロパティ名、3行目以降に値を記述する。プロパティ名は、CSV形式で1行のみ記述する。値は、CSV形式で複数行記述できる。値の行の終端を示すには、空行を挿入する。この変数を参照すると、指定した値の行数分のListで、その要素には、プロパティ名と値が格納されたMapが格納されている。<br>
 *
 * @param tmplateFile テンプレートファイル
 * @param dataFile データファイル
 * @param outputFile 出力ファイル
 * @param encoding 文字エンコーディング。テンプレートファイル、データファイルは、同じ文字エンコーディングである必要があり、出力ファイルも、この文字エンコーディングとなる。
 * @exception Exception 変換に失敗した場合
 */
public void transform(File tmplateFile, File dataFile, File outputFile, String encoding) throws Exception {
    if (dataFile == null) {
        final FileInputStream fis = new FileInputStream(templateResourceDirectory == null ? tmplateFile : new File(templateResourceDirectory, tmplateFile.getPath()));
        final FileOutputStream fos = new FileOutputStream(outputFile);
        try {
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = fis.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
        } finally {
            fis.close();
            fos.close();
        }
    } else {
        Template template = encoding == null ? engine.getTemplate(tmplateFile.getPath()) : engine.getTemplate(tmplateFile.getPath(), encoding);
        Context context = new VelocityContext();
        CSVReader reader = csvReader == null ? new CSVReader() : csvReader.cloneReader();
        reader.setReader(encoding == null ? new FileReader(dataFile) : new InputStreamReader(new FileInputStream(dataFile), encoding));
        try {
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (line.length() == 0) {
                    continue;
                }
                final int index = line.indexOf("=");
                if (index == -1) {
                    String name = line;
                    String[] propNames = reader.readCSVLine();
                    List propValues = null;
                    List records = new ArrayList();
                    while ((propValues = reader.readCSVLineList(propValues)) != null && propValues.size() != 0) {
                        Map record = new HashMap();
                        for (int i = 0; i < propNames.length; i++) {
                            String value = replaceProperty((String) propValues.get(i));
                            record.put(propNames[i], value);
                        }
                        records.add(record);
                    }
                    context.put(name, records);
                } else {
                    String value = replaceProperty(line.substring(index + 1));
                    context.put(line.substring(0, index), value);
                }
            }
        } finally {
            reader.close();
            reader = null;
        }
        Writer writer = encoding == null ? new FileWriter(outputFile) : new OutputStreamWriter(new FileOutputStream(outputFile), encoding);
        try {
            template.merge(context, writer);
        } finally {
            writer.close();
            writer = null;
        }
    }
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) Context(org.apache.velocity.context.Context) InputStreamReader(java.io.InputStreamReader) CSVReader(jp.ossc.nimbus.io.CSVReader) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) FileInputStream(java.io.FileInputStream) Template(org.apache.velocity.Template) FileOutputStream(java.io.FileOutputStream) FileReader(java.io.FileReader) ArrayList(java.util.ArrayList) List(java.util.List) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) FileWriter(java.io.FileWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Aggregations

Context (org.apache.velocity.context.Context)41 VelocityContext (org.apache.velocity.VelocityContext)33 StringWriter (java.io.StringWriter)9 IOException (java.io.IOException)8 Identity (org.olat.core.id.Identity)8 File (java.io.File)6 ArrayList (java.util.ArrayList)6 AssessmentRenderFunctions.contentAsString (org.olat.ims.qti21.ui.components.AssessmentRenderFunctions.contentAsString)6 ApsSystemException (com.agiletec.aps.system.exception.ApsSystemException)4 StringReader (java.io.StringReader)4 Locale (java.util.Locale)4 Map (java.util.Map)4 SubscriptionContext (org.olat.core.commons.services.notifications.SubscriptionContext)4 ValidationError (org.olat.core.gui.components.form.ValidationError)4 MailContext (org.olat.core.util.mail.MailContext)4 I18nManagerWrapper (com.agiletec.aps.system.services.i18n.I18nManagerWrapper)3 InputStream (java.io.InputStream)3 HashMap (java.util.HashMap)3 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)3 Renderer (org.olat.core.gui.render.Renderer)3