Search in sources :

Example 6 with XWikiURLFactory

use of com.xpn.xwiki.web.XWikiURLFactory 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 7 with XWikiURLFactory

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

the class DefaultXWikiStubContextProvider method initialize.

@Override
public void initialize(XWikiContext context) {
    XWikiContext newContext = context.clone();
    newContext.setCacheDuration(0);
    newContext.setUserReference(null);
    newContext.setLocale(null);
    newContext.setWikiId(context.getMainXWiki());
    // Cleanup
    newContext.flushClassCache();
    // So we force the dummy request with the current host
    if (newContext.getRequest() != null) {
        XWikiServletRequestStub initialRequest = new XWikiServletRequestStub();
        initialRequest.setHost(newContext.getRequest().getHeader("x-forwarded-host"));
        initialRequest.setScheme(newContext.getRequest().getScheme());
        XWikiServletRequest request = new XWikiServletRequest(initialRequest);
        newContext.setRequest(request);
    }
    // Get rid of the real response
    if (newContext.getResponse() != null) {
        XWikiServletResponseStub initialResponse = new XWikiServletResponseStub();
        // anything to keep ?
        XWikiServletResponse response = new XWikiServletResponse(initialResponse);
        newContext.setResponse(response);
    }
    // We decide arbitrarily to use the Servlet URL Factory since it's the "standard" factory.
    if (newContext.getURLFactory() != null) {
        XWikiURLFactory urlf = newContext.getWiki().getURLFactoryService().createURLFactory(XWikiContext.MODE_SERVLET, context);
        newContext.setURLFactory(urlf);
    }
    this.initialContext = newContext;
    this.logger.debug("Stub context initialized.");
}
Also used : XWikiServletRequest(com.xpn.xwiki.web.XWikiServletRequest) XWikiURLFactory(com.xpn.xwiki.web.XWikiURLFactory) XWikiServletRequestStub(com.xpn.xwiki.web.XWikiServletRequestStub) XWikiServletResponseStub(com.xpn.xwiki.web.XWikiServletResponseStub) XWikiServletResponse(com.xpn.xwiki.web.XWikiServletResponse) XWikiContext(com.xpn.xwiki.XWikiContext)

Example 8 with XWikiURLFactory

use of com.xpn.xwiki.web.XWikiURLFactory 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 9 with XWikiURLFactory

use of com.xpn.xwiki.web.XWikiURLFactory in project celements-blog by celements.

the class NewsletterReceiversTest method unsubscribeLink.

private void unsubscribeLink(String email) throws Exception {
    String spaceName = "TestSpace";
    String docName = "BlogArticle";
    String urlParams = "xpage=celements_ajax&ajax_mode=BlogAjax&doaction=unsubscribe&emailadresse=";
    String urlStaticPart = "http://celements.com/" + spaceName + "/" + docName + "?" + urlParams;
    URL url = new URL(urlStaticPart + URLEncoder.encode(email, UTF_8.name()));
    IBlogServiceRole blogServiceMock = registerComponentMock(IBlogServiceRole.class);
    XWikiDocument doc = new XWikiDocument(new DocumentReference(getContext().getDatabase(), spaceName, docName));
    BaseObject blogObj = new BaseObject();
    blogObj.setXClassReference(new DocumentReference(getContext().getDatabase(), "Celements2", "BlogConfigClass"));
    blogObj.setIntValue("unsubscribe_info", 1);
    doc.addXObject(blogObj);
    expect(blogServiceMock.getBlogPageByBlogSpace(eq(spaceName))).andReturn(doc);
    XWikiURLFactory urlFactoryMock = createMockAndAddToDefault(XWikiURLFactory.class);
    getContext().setURLFactory(urlFactoryMock);
    expect(urlFactoryMock.createExternalURL(eq(spaceName), eq(docName), eq("view"), eq(urlParams + URLEncoder.encode(email, UTF_8.name())), (String) eq(null), eq(getContext().getDatabase()), same(getContext()))).andReturn(url);
    replayDefault();
    String link = comp.getUnsubscribeLink(spaceName, email);
    verifyDefault();
    assertEquals(url.toString(), link);
}
Also used : XWikiURLFactory(com.xpn.xwiki.web.XWikiURLFactory) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) IBlogServiceRole(com.celements.blog.service.IBlogServiceRole) URL(java.net.URL) DocumentReference(org.xwiki.model.reference.DocumentReference) BaseObject(com.xpn.xwiki.objects.BaseObject)

Example 10 with XWikiURLFactory

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

the class XWikiContextCopierTest method setup.

@Before
public void setup() throws Exception {
    Utils.setComponentManager(mocker);
    originalResponse = new XWikiServletResponseStub();
    original = new XWikiContext();
    // Set some values
    original.setWikiId("wiki");
    DocumentReference userReference = new DocumentReference("wiki", "Space", "Page");
    EntityReferenceSerializer<String> serializer = mocker.registerMockComponent(EntityReferenceSerializer.TYPE_STRING, "compactwiki");
    when(serializer.serialize(userReference)).thenReturn("wiki:Space.Page");
    mocker.registerMockComponent(DocumentReferenceResolver.TYPE_STRING, "currentmixed");
    original.setUserReference(userReference);
    // Set the mock request
    this.originalRequest = mock(XWikiRequest.class);
    original.setRequest(this.originalRequest);
    Copier<XWikiRequest> requestCopier = mocker.getInstance(new DefaultParameterizedType(null, Copier.class, XWikiRequest.class));
    when(requestCopier.copy(this.originalRequest)).thenReturn(this.originalRequest);
    // Set the stubbed response
    original.setResponse(originalResponse);
    // XWiki mock
    XWiki xwiki = mock(XWiki.class);
    original.setWiki(xwiki);
    // Store mock
    // Simulate the existence of a hibernate session in context
    original.put(HIBSESSION, "opened session");
    store = mock(XWikiStoreInterface.class);
    // clean up will remove the session in the given context
    doAnswer(new Answer<Void>() {

        public Void answer(InvocationOnMock invocation) {
            XWikiContext context = (XWikiContext) invocation.getArguments()[0];
            context.put(HIBSESSION, null);
            return null;
        }
    }).when(store).cleanUp(any(XWikiContext.class));
    when(xwiki.getStore()).thenReturn(store);
    // URL factory mock
    XWikiURLFactory urlFactory = mock(XWikiURLFactory.class);
    XWikiURLFactoryService urlFactoryService = mock(XWikiURLFactoryService.class);
    when(urlFactoryService.createURLFactory(anyInt(), any(XWikiContext.class))).thenReturn(urlFactory);
    when(xwiki.getURLFactoryService()).thenReturn(urlFactoryService);
}
Also used : XWikiRequest(com.xpn.xwiki.web.XWikiRequest) XWikiURLFactory(com.xpn.xwiki.web.XWikiURLFactory) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) XWikiURLFactoryService(com.xpn.xwiki.web.XWikiURLFactoryService) XWikiStoreInterface(com.xpn.xwiki.store.XWikiStoreInterface) XWikiServletResponseStub(com.xpn.xwiki.web.XWikiServletResponseStub) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType) DocumentReference(org.xwiki.model.reference.DocumentReference) Before(org.junit.Before)

Aggregations

XWikiURLFactory (com.xpn.xwiki.web.XWikiURLFactory)16 XWikiContext (com.xpn.xwiki.XWikiContext)10 URL (java.net.URL)6 DocumentReference (org.xwiki.model.reference.DocumentReference)6 Test (org.junit.Test)4 ExternalServletURLFactory (com.xpn.xwiki.web.ExternalServletURLFactory)3 XWikiServletResponseStub (com.xpn.xwiki.web.XWikiServletResponseStub)3 XWiki (com.xpn.xwiki.XWiki)2 XWikiException (com.xpn.xwiki.XWikiException)2 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)2 BaseObject (com.xpn.xwiki.objects.BaseObject)2 IOException (java.io.IOException)2 Locale (java.util.Locale)2 MessagingException (javax.mail.MessagingException)2 VelocityContext (org.apache.velocity.VelocityContext)2 IBlogServiceRole (com.celements.blog.service.IBlogServiceRole)1 Document (com.xpn.xwiki.api.Document)1 WikiSkin (com.xpn.xwiki.internal.skin.WikiSkin)1 XWikiStoreInterface (com.xpn.xwiki.store.XWikiStoreInterface)1 XWikiRequest (com.xpn.xwiki.web.XWikiRequest)1