Search in sources :

Example 76 with VelocityContext

use of org.apache.velocity.VelocityContext in project OpenOLAT by OpenOLAT.

the class ProjectBrokerMailerImpl method createMailTemplate.

/**
 * Create default template which fill in context 'firstname' , 'lastname' and 'username'.
 * @param subject
 * @param body
 * @return
 */
private MailTemplate createMailTemplate(Project project, Identity enrolledIdentity, String subject, String body, Locale locale) {
    final String projectTitle = project.getTitle();
    final String currentDate = Formatter.getInstance(locale).formatDateAndTime(new Date());
    final String firstNameEnrolledIdentity = enrolledIdentity.getUser().getProperty(UserConstants.FIRSTNAME, null);
    final String lastnameEnrolledIdentity = enrolledIdentity.getUser().getProperty(UserConstants.LASTNAME, null);
    final String usernameEnrolledIdentity = enrolledIdentity.getName();
    return new MailTemplate(subject, body, null) {

        @Override
        public void putVariablesInMailContext(VelocityContext context, Identity identity) {
            context.put("enrolled_identity_firstname", firstNameEnrolledIdentity);
            context.put("enrolled_identity_lastname", lastnameEnrolledIdentity);
            context.put("enrolled_identity_username", usernameEnrolledIdentity);
            // Put variables from greater context
            context.put("projectTitle", projectTitle);
            context.put("currentDate", currentDate);
        }
    };
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) MailTemplate(org.olat.core.util.mail.MailTemplate) Identity(org.olat.core.id.Identity) Date(java.util.Date)

Example 77 with VelocityContext

use of org.apache.velocity.VelocityContext in project OpenOLAT by OpenOLAT.

the class ProjectBrokerMailerImpl method createProjectChangeMailTemplate.

/**
 * Create default template which fill in context 'firstname' , 'lastname' and 'username'.
 * @param subject
 * @param body
 * @return
 */
private MailTemplate createProjectChangeMailTemplate(Project project, Identity changer, String subject, String body, Locale locale) {
    final String projectTitle = project.getTitle();
    final String currentDate = Formatter.getInstance(locale).formatDateAndTime(new Date());
    final String firstnameProjectManager = changer.getUser().getProperty(UserConstants.FIRSTNAME, null);
    final String lastnameProjectManager = changer.getUser().getProperty(UserConstants.LASTNAME, null);
    final String usernameProjectManager = changer.getName();
    return new MailTemplate(subject, body, null) {

        @Override
        public void putVariablesInMailContext(VelocityContext context, Identity identity) {
            // Put variables from greater context
            context.put("projectTitle", projectTitle);
            context.put("currentDate", currentDate);
            context.put("firstnameProjectManager", firstnameProjectManager);
            context.put("lastnameProjectManager", lastnameProjectManager);
            context.put("usernameProjectManager", usernameProjectManager);
        }
    };
}
Also used : VelocityContext(org.apache.velocity.VelocityContext) MailTemplate(org.olat.core.util.mail.MailTemplate) Identity(org.olat.core.id.Identity) Date(java.util.Date)

Example 78 with VelocityContext

use of org.apache.velocity.VelocityContext in project OpenOLAT by OpenOLAT.

the class CPOfflineReadableManager method writeOfflineCPStartHTMLFile.

/**
 * generates a html-file (_START_.html) that presents the given cp-content
 * (specified by its "_unzipped_"-dir). The resulting file is suitable for
 * offline reading of the cp.
 *
 * @param unzippedDir
 *            the directory that contains the unzipped CP
 */
private void writeOfflineCPStartHTMLFile(File unzippedDir) throws IOException {
    /* first, we do the menu-tree */
    File mani = new File(unzippedDir, FILENAME_IMSMANIFEST);
    LocalFileImpl vfsMani = new LocalFileImpl(mani);
    CPManifestTreeModel ctm = new CPManifestTreeModel(vfsMani, "");
    TreeNode root = ctm.getRootNode();
    // let's take the rootnode title as  page title
    this.rootTitle = root.getTitle();
    StringBuilder menuTreeSB = new StringBuilder();
    renderMenuTreeNodeRecursively(root, menuTreeSB, 0);
    // now put values to velocityContext
    VelocityContext ctx = new VelocityContext();
    ctx.put("menutree", menuTreeSB.toString());
    ctx.put("rootTitle", this.rootTitle);
    ctx.put("cpoff", DIRNAME_CPOFFLINEMENUMAT);
    StringWriter sw = new StringWriter();
    try {
        String template = FileUtils.load(CPOfflineReadableManager.class.getResourceAsStream("_content/cpofflinereadable.html"), "utf-8");
        boolean evalResult = velocityEngine.evaluate(ctx, sw, "cpexport", template);
        if (!evalResult)
            log.error("Could not evaluate velocity template for CP Export");
    } catch (Exception e) {
        log.error("Error while evaluating velovity template for CP Export", e);
    }
    File f = new File(unzippedDir, FILENAME_START);
    if (f.exists()) {
        FileUtils.deleteDirsAndFiles(f, false, true);
    }
    ExportUtil.writeContentToFile(FILENAME_START, sw.toString(), unzippedDir, "utf-8");
}
Also used : StringWriter(java.io.StringWriter) TreeNode(org.olat.core.gui.components.tree.TreeNode) VelocityContext(org.apache.velocity.VelocityContext) LocalFileImpl(org.olat.core.util.vfs.LocalFileImpl) File(java.io.File) IOException(java.io.IOException)

Example 79 with VelocityContext

use of org.apache.velocity.VelocityContext in project OpenOLAT by OpenOLAT.

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 80 with VelocityContext

use of org.apache.velocity.VelocityContext in project OpenOLAT by OpenOLAT.

the class BGMailHelper method createMailTemplate.

/**
 * Internal helper - does all the magic
 *
 * @param group
 * @param actor
 * @param subjectKey
 * @param bodyKey
 * @return
 */
private static MailTemplate createMailTemplate(BusinessGroupShort group, Identity actor, String subjectKey, String bodyKey) {
    // get some data about the actor and fetch the translated subject / body via i18n module
    String[] bodyArgs = null;
    String lang = null;
    if (actor != null) {
        lang = actor.getUser().getPreferences().getLanguage();
    }
    Locale locale = I18nManager.getInstance().getLocaleOrDefault(lang);
    if (actor != null) {
        bodyArgs = new String[] { actor.getUser().getProperty(UserConstants.FIRSTNAME, null), actor.getUser().getProperty(UserConstants.LASTNAME, null), UserManager.getInstance().getUserDisplayEmail(actor, locale), // 2x for compatibility with old i18m properties
        UserManager.getInstance().getUserDisplayEmail(actor, locale) };
    }
    Translator trans = Util.createPackageTranslator(BGMailHelper.class, locale, Util.createPackageTranslator(BusinessGroupListController.class, locale));
    String subject = trans.translate(subjectKey);
    String body = trans.translate(bodyKey, bodyArgs);
    // build learning resources as list of url as string
    final BGMailTemplateInfos infos;
    if (group != null) {
        BusinessGroupService businessGroupService = CoreSpringFactory.getImpl(BusinessGroupService.class);
        List<RepositoryEntryShort> repoEntries = businessGroupService.findShortRepositoryEntries(Collections.singletonList(group), 0, -1);
        infos = getTemplateInfos(group, repoEntries);
        subject = subject.replace("$groupname", infos.getGroupName());
        body = body.replace("$groupname", infos.getGroupNameWithUrl());
        body = body.replace("$groupdescription", infos.getGroupDescription());
        if (StringHelper.containsNonWhitespace(infos.getCourseList())) {
            body = body.replace("$courselist", infos.getCourseList());
        } else {
            body = body.replace("$courselist", trans.translate("notification.mail.no.ressource", null));
        }
    } else {
        infos = new BGMailTemplateInfos("", "", "", "");
    }
    // create a mail template which all these data
    MailTemplate mailTempl = new MailTemplate(subject, body, null) {

        @Override
        public void putVariablesInMailContext(VelocityContext context, Identity identity) {
            // Put user variables into velocity context
            User user = identity.getUser();
            context.put("firstname", user.getProperty(UserConstants.FIRSTNAME, null));
            context.put("lastname", user.getProperty(UserConstants.LASTNAME, null));
            // the email of the user, needs to stay named 'login'
            context.put("login", user.getProperty(UserConstants.EMAIL, null));
            // Put variables from greater context
            context.put("groupname", infos.getGroupNameWithUrl());
            context.put("groupdescription", infos.getGroupDescription());
            if (StringHelper.containsNonWhitespace(infos.getCourseList())) {
                context.put("courselist", infos.getCourseList());
            } else {
                context.put("courselist", trans.translate("notification.mail.no.ressource", null));
            }
            context.put("courselistempty", trans.translate("notification.mail.no.ressource", null));
        }
    };
    return mailTempl;
}
Also used : Locale(java.util.Locale) User(org.olat.core.id.User) RepositoryEntryShort(org.olat.repository.RepositoryEntryShort) VelocityContext(org.apache.velocity.VelocityContext) Translator(org.olat.core.gui.translator.Translator) BusinessGroupService(org.olat.group.BusinessGroupService) MailTemplate(org.olat.core.util.mail.MailTemplate) Identity(org.olat.core.id.Identity) BusinessGroupListController(org.olat.group.ui.main.BusinessGroupListController)

Aggregations

VelocityContext (org.apache.velocity.VelocityContext)492 StringWriter (java.io.StringWriter)156 Template (org.apache.velocity.Template)120 Test (org.junit.Test)72 IOException (java.io.IOException)60 VelocityEngine (org.apache.velocity.app.VelocityEngine)53 File (java.io.File)47 ArrayList (java.util.ArrayList)39 HashMap (java.util.HashMap)36 Map (java.util.Map)36 Identity (org.olat.core.id.Identity)36 Context (org.apache.velocity.context.Context)32 MailTemplate (org.olat.core.util.mail.MailTemplate)28 Writer (java.io.Writer)22 Properties (java.util.Properties)20 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)19 ParseErrorException (org.apache.velocity.exception.ParseErrorException)16 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)16 FileWriter (java.io.FileWriter)15 OutputStreamWriter (java.io.OutputStreamWriter)14