Search in sources :

Example 1 with ExternalServletURLFactory

use of com.xpn.xwiki.web.ExternalServletURLFactory in project xwiki-platform by xwiki.

the class MailSenderPlugin method sendMailFromTemplate.

/**
 * Uses an XWiki document to build the message subject and context, based on variables stored in the
 * VelocityContext. Sends the email.
 *
 * @param templateDocFullName Full name of the template to be used (example: XWiki.MyEmailTemplate). The template
 *            needs to have an XWiki.Email object attached
 * @param from Email sender
 * @param to Email recipient
 * @param cc Email Carbon Copy
 * @param bcc Email Hidden Carbon Copy
 * @param language Language of the email
 * @param vcontext Velocity context passed to the velocity renderer
 * @return True if the email has been sent
 */
public int sendMailFromTemplate(String templateDocFullName, String from, String to, String cc, String bcc, String language, VelocityContext vcontext, XWikiContext context) throws XWikiException {
    XWikiURLFactory originalURLFactory = context.getURLFactory();
    Locale originalLocale = context.getLocale();
    try {
        context.setURLFactory(new ExternalServletURLFactory(context));
        context.setLocale(LocaleUtils.toLocale(language));
        VelocityContext updatedVelocityContext = prepareVelocityContext(from, to, cc, bcc, vcontext, context);
        XWiki xwiki = context.getWiki();
        XWikiDocument doc = xwiki.getDocument(templateDocFullName, context);
        Document docApi = new Document(doc, context);
        BaseObject obj = doc.getObject(EMAIL_XWIKI_CLASS_NAME, "language", language);
        if (obj == null) {
            obj = doc.getObject(EMAIL_XWIKI_CLASS_NAME, "language", "en");
        }
        if (obj == null) {
            LOGGER.error("No mail object found in the document " + templateDocFullName);
            return ERROR_TEMPLATE_EMAIL_OBJECT_NOT_FOUND;
        }
        String subjectContent = obj.getStringValue("subject");
        String txtContent = obj.getStringValue("text");
        String htmlContent = obj.getStringValue("html");
        String subject = evaluate(subjectContent, templateDocFullName, updatedVelocityContext, context);
        String msg = evaluate(txtContent, templateDocFullName, updatedVelocityContext, context);
        String html = evaluate(htmlContent, templateDocFullName, updatedVelocityContext, context);
        Mail mail = new Mail();
        mail.setFrom((String) updatedVelocityContext.get("from.address"));
        mail.setTo((String) updatedVelocityContext.get("to.address"));
        mail.setCc((String) updatedVelocityContext.get("to.cc"));
        mail.setBcc((String) updatedVelocityContext.get("to.bcc"));
        mail.setSubject(subject);
        mail.setTextPart(msg);
        mail.setHtmlPart(html);
        mail.setAttachments(docApi.getAttachmentList());
        try {
            sendMail(mail, context);
            return 0;
        } catch (Exception e) {
            LOGGER.error("sendEmailFromTemplate: " + templateDocFullName + " vcontext: " + updatedVelocityContext, e);
            return ERROR;
        }
    } finally {
        context.setURLFactory(originalURLFactory);
        context.setLocale(originalLocale);
    }
}
Also used : Locale(java.util.Locale) XWikiURLFactory(com.xpn.xwiki.web.XWikiURLFactory) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ExternalServletURLFactory(com.xpn.xwiki.web.ExternalServletURLFactory) VelocityContext(org.apache.velocity.VelocityContext) XWiki(com.xpn.xwiki.XWiki) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException) MessagingException(javax.mail.MessagingException) SendFailedException(javax.mail.SendFailedException) AddressException(javax.mail.internet.AddressException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) BaseObject(com.xpn.xwiki.objects.BaseObject)

Example 2 with ExternalServletURLFactory

use of com.xpn.xwiki.web.ExternalServletURLFactory in project xwiki-platform by xwiki.

the class EmailTemplateRenderer method executeTemplate.

/**
 * Execute a template.
 *
 * @param event composite event to render
 * @param userId id of the user who will receive the email
 * @param template the template to use
 * @param syntax syntax of the template and of the output
 * @return the rendered template
 * @throws NotificationException if something wrong happens
 */
public Block executeTemplate(CompositeEvent event, String userId, Template template, Syntax syntax) throws NotificationException {
    XWikiContext context = contextProvider.get();
    XWikiURLFactory originalURLFactory = context.getURLFactory();
    ScriptContext scriptContext = scriptContextManager.getScriptContext();
    try {
        // Bind the event to some variable in the velocity context
        scriptContext.setAttribute(EVENT_BINDING_NAME, event, ScriptContext.ENGINE_SCOPE);
        scriptContext.setAttribute(USER_BINDING_NAME, userId, ScriptContext.ENGINE_SCOPE);
        // Use the external URL factory to generate full URLs
        context.setURLFactory(new ExternalServletURLFactory(context));
        // Set the given syntax in the rendering context
        if (renderingContext instanceof MutableRenderingContext) {
            ((MutableRenderingContext) renderingContext).push(null, null, syntax, null, false, syntax);
        }
        // Render the template or fallback to the default one
        return templateManager.execute(template);
    } catch (Exception e) {
        throw new NotificationException("Failed to render the notification.", e);
    } finally {
        // Cleaning the rendering context
        if (renderingContext instanceof MutableRenderingContext) {
            ((MutableRenderingContext) renderingContext).pop();
        }
        // Cleaning the URL factory
        context.setURLFactory(originalURLFactory);
        // Cleaning the velocity context
        scriptContext.removeAttribute(EVENT_BINDING_NAME, ScriptContext.ENGINE_SCOPE);
        scriptContext.removeAttribute(USER_BINDING_NAME, ScriptContext.ENGINE_SCOPE);
    }
}
Also used : XWikiURLFactory(com.xpn.xwiki.web.XWikiURLFactory) ExternalServletURLFactory(com.xpn.xwiki.web.ExternalServletURLFactory) NotificationException(org.xwiki.notifications.NotificationException) XWikiContext(com.xpn.xwiki.XWikiContext) ScriptContext(javax.script.ScriptContext) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext) NotificationException(org.xwiki.notifications.NotificationException)

Example 3 with ExternalServletURLFactory

use of com.xpn.xwiki.web.ExternalServletURLFactory in project xwiki-platform by xwiki.

the class DefaultMailTemplateManager method evaluate.

@Override
public String evaluate(DocumentReference templateReference, String property, Map<String, Object> velocityVariables, Object localeValue) throws MessagingException {
    Locale locale = getLocale(localeValue);
    // Note: Make sure to use the class reference relative to the template's wiki and not the current wiki.
    DocumentReference mailClassReference = this.resolver.resolve(MAIL_CLASS, templateReference.getWikiReference());
    VelocityContext velocityContext = createVelocityContext(velocityVariables);
    String templateFullName = this.serializer.serialize(templateReference);
    int objectNumber = getObjectMailNumber(templateReference, mailClassReference, locale);
    String content = this.documentBridge.getProperty(templateReference, mailClassReference, objectNumber, property).toString();
    // Save the current URL Factory since we'll replace it with a URL factory that generates external URLs (ie
    // full URLs).
    XWikiContext xcontext = this.xwikiContextProvider.get();
    XWikiURLFactory originalURLFactory = xcontext.getURLFactory();
    Locale originalLocale = xcontext.getLocale();
    try {
        // Generate full URLs (instead of relative URLs)
        xcontext.setURLFactory(new ExternalServletURLFactory(xcontext));
        // Set the current locale to be the passed locale so that the template content is evaluated in that
        // language (in case there are translations used).
        xcontext.setLocale(locale);
        return velocityEvaluator.evaluateVelocity(content, templateFullName, velocityContext);
    } catch (XWikiException e) {
        throw new MessagingException(String.format("Failed to evaluate property [%s] for Document [%s] and locale [%s]", property, templateReference, localeValue), e);
    } finally {
        xcontext.setURLFactory(originalURLFactory);
        xcontext.setLocale(originalLocale);
    }
}
Also used : Locale(java.util.Locale) XWikiURLFactory(com.xpn.xwiki.web.XWikiURLFactory) ExternalServletURLFactory(com.xpn.xwiki.web.ExternalServletURLFactory) MessagingException(javax.mail.MessagingException) VelocityContext(org.apache.velocity.VelocityContext) XWikiContext(com.xpn.xwiki.XWikiContext) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException)

Aggregations

ExternalServletURLFactory (com.xpn.xwiki.web.ExternalServletURLFactory)3 XWikiURLFactory (com.xpn.xwiki.web.XWikiURLFactory)3 XWikiContext (com.xpn.xwiki.XWikiContext)2 XWikiException (com.xpn.xwiki.XWikiException)2 Locale (java.util.Locale)2 MessagingException (javax.mail.MessagingException)2 VelocityContext (org.apache.velocity.VelocityContext)2 XWiki (com.xpn.xwiki.XWiki)1 Document (com.xpn.xwiki.api.Document)1 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)1 BaseObject (com.xpn.xwiki.objects.BaseObject)1 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 SendFailedException (javax.mail.SendFailedException)1 AddressException (javax.mail.internet.AddressException)1 ScriptContext (javax.script.ScriptContext)1 DocumentReference (org.xwiki.model.reference.DocumentReference)1 NotificationException (org.xwiki.notifications.NotificationException)1 MutableRenderingContext (org.xwiki.rendering.internal.transformation.MutableRenderingContext)1