Search in sources :

Example 31 with Document

use of com.xpn.xwiki.api.Document 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 32 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class ViewAttachRevAction method render.

@Override
public String render(XWikiContext context) throws XWikiException {
    XWikiRequest request = context.getRequest();
    XWikiDocument doc = context.getDoc();
    String filename;
    if (context.getMode() == XWikiContext.MODE_PORTLET) {
        filename = request.getParameter("filename");
    } else {
        filename = getFileName();
    }
    XWikiAttachment attachment;
    if (context.getWiki().hasAttachmentRecycleBin(context) && request.getParameter("rid") != null) {
        int recycleId = Integer.parseInt(request.getParameter("rid"));
        attachment = new XWikiAttachment(doc, filename);
        attachment = context.getWiki().getAttachmentRecycleBinStore().restoreFromRecycleBin(attachment, recycleId, context, true);
    } else if (request.getParameter("id") != null) {
        int id = Integer.parseInt(request.getParameter("id"));
        attachment = doc.getAttachmentList().get(id);
    } else {
        attachment = doc.getAttachment(filename);
        if (attachment == null) {
            context.put("message", "attachmentdoesnotexist");
            return "exception";
        }
    }
    ScriptContext scriptContext = getCurrentScriptContext();
    scriptContext.setAttribute("attachment", new Attachment((Document) scriptContext.getAttribute("doc"), attachment, context), ScriptContext.ENGINE_SCOPE);
    return "viewattachrev";
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ScriptContext(javax.script.ScriptContext) Attachment(com.xpn.xwiki.api.Attachment) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Document(com.xpn.xwiki.api.Document)

Example 33 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class LogoAttachmentExtractor method getLogo.

/**
 * @return an attachment holding the logo of the wiki
 * @throws Exception if an error happens
 */
public Attachment getLogo() throws Exception {
    XWikiContext context = xwikiContextProvider.get();
    String colorTheme = configurationSource.getProperty("colorTheme");
    if (StringUtils.isNotBlank(colorTheme)) {
        DocumentReference colorThemeRef = documentReferenceResolver.resolve(colorTheme);
        XWiki xwiki = context.getWiki();
        XWikiDocument doc = xwiki.getDocument(colorThemeRef, context);
        String logo = doc.getStringValue(LOGO);
        if (StringUtils.isBlank(logo)) {
            logo = doc.getStringValue("logoImage");
        }
        if (isLogoAttachementValid(doc, logo)) {
            XWikiAttachment attachment = doc.getAttachment(logo);
            attachment.setFilename(LOGO);
            return new Attachment(new Document(doc, context), attachment, context);
        }
    }
    String skin = configurationSource.getProperty("skin");
    if (StringUtils.isNotBlank(skin)) {
        DocumentReference skinRef = documentReferenceResolver.resolve(skin);
        XWiki xwiki = context.getWiki();
        XWikiDocument doc = xwiki.getDocument(skinRef, context);
        String logo = doc.getStringValue(LOGO);
        if (isLogoAttachementValid(doc, logo)) {
            XWikiAttachment attachment = doc.getAttachment(logo);
            attachment.setFilename(LOGO);
            return new Attachment(new Document(doc, context), attachment, context);
        }
    }
    XWikiAttachment fakeAttachment = new XWikiAttachment();
    Resource sourceImageIS = internalSkinManager.getCurrentSkin(true).getResource("logo.png");
    InputStream inputStream = environment.getResourceAsStream(sourceImageIS.getPath());
    fakeAttachment.setAttachment_content(new XWikiAttachmentContent());
    fakeAttachment.getAttachment_content().setContent(inputStream);
    fakeAttachment.setFilename(LOGO);
    return new Attachment(null, fakeAttachment, context);
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) InputStream(java.io.InputStream) Resource(org.xwiki.skin.Resource) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Attachment(com.xpn.xwiki.api.Attachment) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiAttachmentContent(com.xpn.xwiki.doc.XWikiAttachmentContent)

Example 34 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class XWikiDocumentRenderingTest method testGetRenderedContentCleansVelocityMacroCache.

/**
 * See XWIKI-5277 for details.
 */
public void testGetRenderedContentCleansVelocityMacroCache() throws Exception {
    // Make sure we start not in the rendering engine since this is what happens in real: a document is
    // called by a template thus outside of the rendering engine.
    getContext().remove("isInRenderingEngine");
    // We display a text area since we know that rendering a text area will call getRenderedContent inside our top
    // level getRenderedContent call, thus testing that velocity macros are not removed during nested calls to
    // getRenderedContent.
    this.baseObject.setLargeStringValue("area", "{{velocity}}#macro(testmacrocache)ok#end{{/velocity}}");
    this.document.setContent("{{velocity}}$doc.display(\"area\")#testmacrocache{{/velocity}}");
    this.document.setSyntax(Syntax.XWIKI_2_0);
    // We need to put the current doc in the Velocity Context since it's normally set before the rendering is
    // called in the execution flow.
    VelocityManager originalVelocityManager = getComponentManager().getInstance(VelocityManager.class);
    VelocityContext vcontext = originalVelocityManager.getVelocityContext();
    vcontext.put("doc", new Document(this.document, getContext()));
    // Register a Mock for the VelocityManager to bypass skin APIs that we would need to mock otherwise.
    Mock mockVelocityManager = registerMockComponent(VelocityManager.class);
    mockVelocityManager.stubs().method("getCurrentVelocityContext").will(returnValue(vcontext));
    VelocityFactory velocityFactory = getComponentManager().getInstance(VelocityFactory.class);
    VelocityEngine vengine = velocityFactory.createVelocityEngine("default", new Properties());
    // Save the number of cached macro templates in the Velocity engine so that we can compare after the
    // document is rendered.
    JMXVelocityEngineMBean mbean = new JMXVelocityEngine(vengine);
    int cachedMacroNamespaceSize = mbean.getTemplates().values().size();
    assertTrue(cachedMacroNamespaceSize > 0);
    mockVelocityManager.stubs().method("getVelocityEngine").will(returnValue(vengine));
    mockVelocityManager.stubs().method("evaluate").will(new CustomStub("evaluate") {

        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            return vengine.evaluate(vcontext, (Writer) invocation.parameterValues.get(0), (String) invocation.parameterValues.get(1), (Reader) invocation.parameterValues.get(2));
        }
    });
    // $doc.display will ask for the syntax of the current document so we need to mock it.
    this.mockXWiki.stubs().method("getCurrentContentSyntaxId").with(eq("xwiki/2.0"), ANYTHING).will(returnValue("xwiki/2.0"));
    // Verify that the macro located inside the TextArea has been taken into account when executing the doc's
    // content.
    assertEquals("<p>ok</p>", this.document.getRenderedContent(getContext()));
    // Now verify that the Velocity Engine doesn't contain any more cached macro namespace to prove that
    // getRenderedContent has correctly cleaned the Velocity macro cache.
    assertEquals(cachedMacroNamespaceSize, mbean.getTemplates().values().size());
}
Also used : VelocityEngine(org.xwiki.velocity.VelocityEngine) JMXVelocityEngine(org.xwiki.velocity.internal.jmx.JMXVelocityEngine) Invocation(org.jmock.core.Invocation) VelocityFactory(org.xwiki.velocity.VelocityFactory) VelocityContext(org.apache.velocity.VelocityContext) JMXVelocityEngineMBean(org.xwiki.velocity.internal.jmx.JMXVelocityEngineMBean) Reader(java.io.Reader) Document(com.xpn.xwiki.api.Document) Properties(java.util.Properties) Mock(org.jmock.Mock) JMXVelocityEngine(org.xwiki.velocity.internal.jmx.JMXVelocityEngine) CustomStub(org.jmock.core.stub.CustomStub) VelocityManager(org.xwiki.velocity.VelocityManager) BaseObject(com.xpn.xwiki.objects.BaseObject) Writer(java.io.Writer)

Example 35 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class SheetScriptServiceTest method bindClassSheetClonesDocument.

/**
 * Tests that {@link SheetScriptService#bindClassSheet(Document, DocumentReference)} clones the document first to
 * follow the practice from {@link Document}. This is required in order to not modify the cached document.
 *
 * @throws Exception if the test fails to lookup the class sheet binder
 */
@Test
public void bindClassSheetClonesDocument() throws Exception {
    DocumentReference classReference = new DocumentReference("wiki", "Space", "MyClass");
    final XWikiDocument classDocument = new XWikiDocument(classReference);
    classDocument.setSyntax(Syntax.PLAIN_1_0);
    Document classDocumentApi = new Document(classDocument, null);
    final DocumentReference sheetReference = new DocumentReference("MySheet", classReference.getLastSpaceReference());
    when(this.mockClassSheetBinder.bind(argThat(new ArgumentMatcher<DocumentModelBridge>() {

        @Override
        public boolean matches(DocumentModelBridge argument) {
            return classDocument.equals(argument) && classDocument != argument;
        }
    }), same(sheetReference))).thenReturn(true);
    Assert.assertTrue(this.sheetScriptService.bindClassSheet(classDocumentApi, sheetReference));
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) DocumentModelBridge(org.xwiki.bridge.DocumentModelBridge) ArgumentMatcher(org.mockito.ArgumentMatcher) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) DocumentReference(org.xwiki.model.reference.DocumentReference) Test(org.junit.Test)

Aggregations

Document (com.xpn.xwiki.api.Document)97 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)60 XWikiException (com.xpn.xwiki.XWikiException)41 XWikiRestException (org.xwiki.rest.XWikiRestException)40 DocumentReference (org.xwiki.model.reference.DocumentReference)37 BaseObject (com.xpn.xwiki.objects.BaseObject)24 Test (org.junit.Test)23 WebApplicationException (javax.ws.rs.WebApplicationException)22 ArrayList (java.util.ArrayList)16 Attachment (com.xpn.xwiki.api.Attachment)14 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)14 Vector (java.util.Vector)12 Link (org.xwiki.rest.model.jaxb.Link)10 XWikiContext (com.xpn.xwiki.XWikiContext)9 AbstractComponentTest (com.celements.common.test.AbstractComponentTest)7 Date (java.util.Date)7 XWiki (com.xpn.xwiki.api.XWiki)6 RangeIterable (org.xwiki.rest.internal.RangeIterable)6 Object (org.xwiki.rest.model.jaxb.Object)6 XWiki (com.xpn.xwiki.XWiki)5