Search in sources :

Example 26 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class XWikiHibernateAttachmentStore method saveAttachmentsContent.

@Override
public void saveAttachmentsContent(List<XWikiAttachment> attachments, XWikiDocument doc, boolean bParentUpdate, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException {
    if (attachments == null) {
        return;
    }
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(context);
        }
        Iterator<XWikiAttachment> it = attachments.iterator();
        while (it.hasNext()) {
            XWikiAttachment att = it.next();
            saveAttachmentContent(att, false, context, false);
        }
        if (bParentUpdate) {
            context.getWiki().getStore().saveXWikiDoc(doc, context, false);
        }
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT, "Exception while saving attachments", e);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }
        restoreExecutionXContext();
    }
}
Also used : XWikiContext(com.xpn.xwiki.XWikiContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) XWikiException(com.xpn.xwiki.XWikiException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) XWikiException(com.xpn.xwiki.XWikiException)

Example 27 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class XWikiHibernateStore method loadAttachmentList.

private void loadAttachmentList(XWikiDocument doc, XWikiContext context, boolean bTransaction) throws XWikiException {
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(null, context);
        }
        Session session = getSession(context);
        Query query = session.createQuery("from XWikiAttachment as attach where attach.docId=:docid");
        query.setLong("docid", doc.getId());
        @SuppressWarnings("unchecked") List<XWikiAttachment> list = query.list();
        for (XWikiAttachment attachment : list) {
            doc.setAttachment(attachment);
        }
    } catch (Exception e) {
        this.logger.error("Failed to load attachments of document [{}]", doc.getDocumentReference(), e);
        Object[] args = { doc.getDocumentReference() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCHING_ATTACHMENT, "Exception while searching attachments for documents {0}", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }
    }
}
Also used : Query(org.hibernate.Query) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) XWikiException(com.xpn.xwiki.XWikiException) InitializationException(org.xwiki.component.phase.InitializationException) MigrationRequiredException(com.xpn.xwiki.store.migration.MigrationRequiredException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) QueryException(org.xwiki.query.QueryException) UnexpectedException(org.xwiki.store.UnexpectedException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) SQLException(java.sql.SQLException) XWikiException(com.xpn.xwiki.XWikiException) Session(org.hibernate.Session)

Example 28 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class XWikiHibernateStore method saveXWikiDoc.

@Override
public void saveXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException {
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    try {
        MonitorPlugin monitor = Util.getMonitorPlugin(context);
        try {
            // Start monitoring timer
            if (monitor != null) {
                monitor.startTimer(HINT);
            }
            doc.setStore(this);
            // Make sure the database name is stored
            doc.setDatabase(context.getWikiId());
            // If the comment is larger than the max size supported by the Storage, then abbreviate it
            String comment = doc.getComment();
            if (comment != null && comment.length() > 1023) {
                doc.setComment(StringUtils.abbreviate(comment, 1023));
            }
            if (bTransaction) {
                checkHibernate(context);
                SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
                bTransaction = beginTransaction(sfactory, context);
            }
            Session session = getSession(context);
            session.setFlushMode(FlushMode.COMMIT);
            // These informations will allow to not look for attachments and objects on loading
            doc.setElement(XWikiDocument.HAS_ATTACHMENTS, !doc.getAttachmentList().isEmpty());
            doc.setElement(XWikiDocument.HAS_OBJECTS, !doc.getXObjects().isEmpty());
            // Let's update the class XML since this is the new way to store it
            // TODO If all the properties are removed, the old xml stays?
            BaseClass bclass = doc.getXClass();
            if (bclass != null) {
                if (bclass.getFieldList().isEmpty()) {
                    doc.setXClassXML("");
                } else {
                    // Don't format the XML to reduce the size of the stored data as much as possible
                    doc.setXClassXML(bclass.toXMLString(false));
                }
                bclass.setDirty(false);
            }
            if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) {
                saveAttachmentList(doc, context);
            }
            // Remove attachments planned for removal
            if (!doc.getAttachmentsToRemove().isEmpty()) {
                for (XWikiAttachmentToRemove attachmentToRemove : doc.getAttachmentsToRemove()) {
                    XWikiAttachment attachment = attachmentToRemove.getAttachment();
                    XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
                    store.deleteXWikiAttachment(attachment, false, context, false);
                }
                doc.clearAttachmentsToRemove();
            }
            // Handle the latest text file
            if (doc.isContentDirty() || doc.isMetaDataDirty()) {
                Date ndate = new Date();
                doc.setDate(ndate);
                if (doc.isContentDirty()) {
                    doc.setContentUpdateDate(ndate);
                    doc.setContentAuthorReference(doc.getAuthorReference());
                }
                doc.incrementVersion();
                if (context.getWiki().hasVersioning(context)) {
                    context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
                }
                doc.setContentDirty(false);
                doc.setMetaDataDirty(false);
            } else {
                if (doc.getDocumentArchive() != null) {
                    // This is especially needed if we load a document from XML
                    if (context.getWiki().hasVersioning(context)) {
                        context.getWiki().getVersioningStore().saveXWikiDocArchive(doc.getDocumentArchive(), false, context);
                        // If the version does not exist it means it's a new version so add it to the history
                        if (!containsVersion(doc, doc.getRCSVersion(), context)) {
                            context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
                        }
                    }
                } else {
                    // with a valid context
                    try {
                        if (context.getWiki().hasVersioning(context)) {
                            doc.getDocumentArchive(context);
                            // history
                            if (!containsVersion(doc, doc.getRCSVersion(), context)) {
                                context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
                            }
                        }
                    } catch (XWikiException e) {
                    // this is a non critical error
                    }
                }
            }
            // Verify if the document already exists
            Query query = session.createQuery("select xwikidoc.id from XWikiDocument as xwikidoc where xwikidoc.id = :id");
            query.setLong("id", doc.getId());
            if (query.uniqueResult() == null) {
                if (doc.isContentDirty() || doc.isMetaDataDirty()) {
                    // Reset the creationDate to reflect the date of the first save, not the date of the object
                    // creation
                    doc.setCreationDate(new Date());
                }
                session.save(doc);
            } else {
                session.update(doc);
            // TODO: this is slower!! How can it be improved?
            // session.saveOrUpdate(doc);
            }
            // Remove objects planned for removal
            if (doc.getXObjectsToRemove().size() > 0) {
                for (BaseObject removedObject : doc.getXObjectsToRemove()) {
                    deleteXWikiCollection(removedObject, context, false, false);
                }
                doc.setXObjectsToRemove(new ArrayList<BaseObject>());
            }
            if (bclass != null) {
                bclass.setDocumentReference(doc.getDocumentReference());
                // Store this XWikiClass in the context so that we can use it in case of recursive usage of classes
                context.addBaseClass(bclass);
            }
            if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) {
                // TODO: Delete all objects for which we don't have a name in the Map
                for (List<BaseObject> objects : doc.getXObjects().values()) {
                    for (BaseObject obj : objects) {
                        if (obj != null) {
                            obj.setDocumentReference(doc.getDocumentReference());
                            /* If the object doesn't have a GUID, create it before saving */
                            if (StringUtils.isEmpty(obj.getGuid())) {
                                obj.setGuid(null);
                            }
                            saveXWikiCollection(obj, context, false);
                        }
                    }
                }
            }
            if (context.getWiki().hasBacklinks(context)) {
                try {
                    saveLinks(doc, context, true);
                } catch (Exception e) {
                    this.logger.error("Failed to save links for document [{}]", doc.getDocumentReferenceWithLocale(), e);
                }
            }
            // Update space table
            updateXWikiSpaceTable(doc, session);
            if (bTransaction) {
                endTransaction(context, true);
            }
            doc.setNew(false);
            // We need to ensure that the saved document becomes the original document
            doc.setOriginalDocument(doc.clone());
        } catch (Exception e) {
            Object[] args = { this.defaultEntityReferenceSerializer.serialize(doc.getDocumentReference()) };
            throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_DOC, "Exception while saving document {0}", e, args);
        } finally {
            try {
                if (bTransaction) {
                    endTransaction(context, false);
                }
            } catch (Exception e) {
            }
            // End monitoring timer
            if (monitor != null) {
                monitor.endTimer(HINT);
            }
        }
    } finally {
        restoreExecutionXContext();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) Query(org.hibernate.Query) MonitorPlugin(com.xpn.xwiki.monitor.api.MonitorPlugin) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Date(java.util.Date) XWikiException(com.xpn.xwiki.XWikiException) InitializationException(org.xwiki.component.phase.InitializationException) MigrationRequiredException(com.xpn.xwiki.store.migration.MigrationRequiredException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) QueryException(org.xwiki.query.QueryException) UnexpectedException(org.xwiki.store.UnexpectedException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) SQLException(java.sql.SQLException) BaseObject(com.xpn.xwiki.objects.BaseObject) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) XWikiAttachmentToRemove(com.xpn.xwiki.doc.XWikiDocument.XWikiAttachmentToRemove) XWikiException(com.xpn.xwiki.XWikiException) Session(org.hibernate.Session)

Example 29 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class XWikiHibernateStore method deleteXWikiDoc.

@Override
public void deleteXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException {
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    try {
        boolean bTransaction = true;
        MonitorPlugin monitor = Util.getMonitorPlugin(context);
        try {
            // Start monitoring timer
            if (monitor != null) {
                monitor.startTimer(HINT);
            }
            checkHibernate(context);
            SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
            bTransaction = bTransaction && beginTransaction(sfactory, context);
            Session session = getSession(context);
            session.setFlushMode(FlushMode.COMMIT);
            if (doc.getStore() == null) {
                Object[] args = { doc.getDocumentReference() };
                throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_CANNOT_DELETE_UNLOADED_DOC, "Impossible to delete document {0} if it is not loaded", null, args);
            }
            // Let's delete any attachment this document might have
            for (XWikiAttachment attachment : doc.getAttachmentList()) {
                XWikiAttachmentStoreInterface store = getXWikiAttachmentStoreInterface(attachment);
                store.deleteXWikiAttachment(attachment, false, context, false);
            }
            // deleting XWikiLinks
            if (context.getWiki().hasBacklinks(context)) {
                deleteLinks(doc.getId(), context, true);
            }
            // Remove properties planned for removal
            if (!doc.getXObjectsToRemove().isEmpty()) {
                for (BaseObject bobj : doc.getXObjectsToRemove()) {
                    if (bobj != null) {
                        deleteXWikiCollection(bobj, context, false, false);
                    }
                }
                doc.setXObjectsToRemove(new ArrayList<BaseObject>());
            }
            for (List<BaseObject> objects : doc.getXObjects().values()) {
                for (BaseObject obj : objects) {
                    if (obj != null) {
                        deleteXWikiCollection(obj, context, false, false);
                    }
                }
            }
            context.getWiki().getVersioningStore().deleteArchive(doc, false, context);
            session.delete(doc);
            // We need to ensure that the deleted document becomes the original document
            doc.setOriginalDocument(doc.clone());
            // Update space table if needed
            maybeDeleteXWikiSpace(doc, session);
            if (bTransaction) {
                endTransaction(context, true);
            }
        } catch (Exception e) {
            Object[] args = { doc.getDocumentReference() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_DELETING_DOC, "Exception while deleting document {0}", e, args);
        } finally {
            try {
                if (bTransaction) {
                    endTransaction(context, false);
                }
            } catch (Exception e) {
            }
            // End monitoring timer
            if (monitor != null) {
                monitor.endTimer(HINT);
            }
        }
    } finally {
        restoreExecutionXContext();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) MonitorPlugin(com.xpn.xwiki.monitor.api.MonitorPlugin) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) XWikiException(com.xpn.xwiki.XWikiException) InitializationException(org.xwiki.component.phase.InitializationException) MigrationRequiredException(com.xpn.xwiki.store.migration.MigrationRequiredException) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) QueryException(org.xwiki.query.QueryException) UnexpectedException(org.xwiki.store.UnexpectedException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) SQLException(java.sql.SQLException) BaseObject(com.xpn.xwiki.objects.BaseObject) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiException(com.xpn.xwiki.XWikiException) Session(org.hibernate.Session)

Example 30 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class DownloadActionTest method downloadById.

@Test
public void downloadById() throws XWikiException, IOException {
    Date d = new Date();
    XWikiAttachment att;
    for (byte i = 0; i < 10; ++i) {
        att = new XWikiAttachment(this.document, "file." + i + ".txt");
        byte[] content = new byte[1];
        content[0] = (byte) ('0' + i);
        att.setContent(new ByteArrayInputStream(content));
        att.setDate(d);
        this.document.getAttachmentList().add(att);
    }
    when(this.ec.getMimeType("file.5.txt")).thenReturn("text/plain");
    setRequestExpectations("/xwiki/bin/download/space/page/file.2.txt", "5", null, null, -1l, DEFAULT_FILE_NAME);
    assertNull(this.action.render(this.oldcore.getXWikiContext()));
    verifyResponseExpectations(d.getTime(), 1, "text/plain", "inline; filename*=utf-8''file.5.txt");
    verify(this.out).write(argThat(new ArgumentMatcher<byte[]>() {

        @Override
        public boolean matches(byte[] argument) {
            return argument[0] == '5';
        }
    }), eq(0), eq(1));
    verify(this.out).write(argThat(new ArgumentMatcher<byte[]>() {

        @Override
        public boolean matches(byte[] argument) {
            return argument[0] == '5';
        }
    }), eq(0), eq(1));
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ArgumentMatcher(org.mockito.ArgumentMatcher) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Date(java.util.Date) Test(org.junit.Test)

Aggregations

XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)133 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)71 DocumentReference (org.xwiki.model.reference.DocumentReference)51 Test (org.junit.Test)40 XWikiContext (com.xpn.xwiki.XWikiContext)35 XWikiException (com.xpn.xwiki.XWikiException)25 ByteArrayInputStream (java.io.ByteArrayInputStream)20 Attachment (com.xpn.xwiki.api.Attachment)18 Date (java.util.Date)17 IOException (java.io.IOException)15 ArrayList (java.util.ArrayList)15 Document (com.xpn.xwiki.api.Document)14 XWiki (com.xpn.xwiki.XWiki)13 BaseObject (com.xpn.xwiki.objects.BaseObject)13 AttachmentReference (org.xwiki.model.reference.AttachmentReference)13 InputStream (java.io.InputStream)11 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)10 File (java.io.File)10 URL (java.net.URL)7 List (java.util.List)7