Search in sources :

Example 11 with BaseClass

use of com.xpn.xwiki.objects.classes.BaseClass in project xwiki-platform by xwiki.

the class ExtensionManagerScriptServiceTest method before.

@Before
public void before() throws Exception {
    // mock
    this.mockXWiki = mock(XWiki.class);
    this.xwikiBridge.getXWikiContext().setWiki(this.mockXWiki);
    this.xwikiBridge.getXWikiContext().setWikiId("xwiki");
    this.contextUser = new DocumentReference(this.xwikiBridge.getXWikiContext().getWikiId(), "XWiki", "ExtensionUser");
    // classes
    BaseClass styleSheetClass = new BaseClass();
    this.classes.put("StyleSheetExtension", styleSheetClass);
    // checking
    this.xwikiBridge.getXWikiContext().setUserReference(this.contextUser);
    ((XWikiStubContextProvider) this.mocker.getInstance(XWikiStubContextProvider.class)).initialize(this.xwikiBridge.getXWikiContext());
    // lookup
    this.scriptService = this.mocker.getInstance(ScriptService.class, "extension");
}
Also used : XWikiStubContextProvider(com.xpn.xwiki.util.XWikiStubContextProvider) ScriptService(org.xwiki.script.service.ScriptService) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) XWiki(com.xpn.xwiki.XWiki) DocumentReference(org.xwiki.model.reference.DocumentReference) Before(org.junit.Before)

Example 12 with BaseClass

use of com.xpn.xwiki.objects.classes.BaseClass in project xwiki-platform by xwiki.

the class XWiki method getObjectFromRequest.

// This functions adds an object from an new object creation form
public BaseObject getObjectFromRequest(String className, XWikiContext context) throws XWikiException {
    Map<String, String[]> map = Util.getObject(context.getRequest(), className);
    BaseClass bclass = context.getWiki().getClass(className, context);
    BaseObject newobject = (BaseObject) bclass.fromMap(map, context);
    return newobject;
}
Also used : BaseClass(com.xpn.xwiki.objects.classes.BaseClass) ParseGroovyFromString(com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString) IncludeServletAsString(com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString) BaseObject(com.xpn.xwiki.objects.BaseObject)

Example 13 with BaseClass

use of com.xpn.xwiki.objects.classes.BaseClass in project xwiki-platform by xwiki.

the class Document method getxWikiClasses.

/**
 * @return the array of XClasses representing the objects of this document
 */
public Class[] getxWikiClasses() {
    List<BaseClass> list = this.getDoc().getXClasses(getXWikiContext());
    if (list == null) {
        return null;
    }
    Class[] result = new Class[list.size()];
    for (int i = 0; i < list.size(); i++) {
        result[i] = new Class(list.get(i), getXWikiContext());
    }
    return result;
}
Also used : BaseClass(com.xpn.xwiki.objects.classes.BaseClass) BaseClass(com.xpn.xwiki.objects.classes.BaseClass)

Example 14 with BaseClass

use of com.xpn.xwiki.objects.classes.BaseClass 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 15 with BaseClass

use of com.xpn.xwiki.objects.classes.BaseClass in project xwiki-platform by xwiki.

the class XWikiHibernateStore method loadXWikiDoc.

@Override
public XWikiDocument loadXWikiDoc(XWikiDocument doc, XWikiContext inputxcontext) throws XWikiException {
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    try {
        // To change body of implemented methods use Options | File Templates.
        boolean bTransaction = true;
        MonitorPlugin monitor = Util.getMonitorPlugin(context);
        try {
            // Start monitoring timer
            if (monitor != null) {
                monitor.startTimer(HINT);
            }
            doc.setStore(this);
            checkHibernate(context);
            SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
            bTransaction = bTransaction && beginTransaction(sfactory, context);
            Session session = getSession(context);
            session.setFlushMode(FlushMode.MANUAL);
            try {
                session.load(doc, Long.valueOf(doc.getId()));
                doc.setNew(false);
                doc.setMostRecent(true);
                // Fix for XWIKI-1651
                doc.setDate(new Date(doc.getDate().getTime()));
                doc.setCreationDate(new Date(doc.getCreationDate().getTime()));
                doc.setContentUpdateDate(new Date(doc.getContentUpdateDate().getTime()));
            } catch (ObjectNotFoundException e) {
                // No document
                doc.setNew(true);
                // Make sure to always return a document with an original version, even for one that does not exist.
                // Allow writing more generic code.
                doc.setOriginalDocument(new XWikiDocument(doc.getDocumentReference(), doc.getLocale()));
                return doc;
            }
            // Loading the attachment list
            if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) {
                loadAttachmentList(doc, context, false);
            }
            // TODO: handle the case where there are no xWikiClass and xWikiObject in the Database
            BaseClass bclass = new BaseClass();
            String cxml = doc.getXClassXML();
            if (cxml != null) {
                bclass.fromXML(cxml);
                doc.setXClass(bclass);
                bclass.setDirty(false);
            }
            // 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)) {
                Query query = session.createQuery("from BaseObject as bobject where bobject.name = :name order by bobject.number");
                query.setText("name", doc.getFullName());
                @SuppressWarnings("unchecked") Iterator<BaseObject> it = query.list().iterator();
                EntityReference localGroupEntityReference = new EntityReference("XWikiGroups", EntityType.DOCUMENT, new EntityReference("XWiki", EntityType.SPACE));
                DocumentReference groupsDocumentReference = new DocumentReference(context.getWikiId(), localGroupEntityReference.getParent().getName(), localGroupEntityReference.getName());
                boolean hasGroups = false;
                while (it.hasNext()) {
                    BaseObject object = it.next();
                    DocumentReference classReference = object.getXClassReference();
                    if (classReference == null) {
                        continue;
                    }
                    // object which doesn't really belong to this document
                    if (!object.getDocumentReference().equals(doc.getDocumentReference())) {
                        continue;
                    }
                    BaseObject newobject;
                    if (classReference.equals(doc.getDocumentReference())) {
                        newobject = bclass.newCustomClassInstance(context);
                    } else {
                        newobject = BaseClass.newCustomClassInstance(classReference, context);
                    }
                    if (newobject != null) {
                        newobject.setId(object.getId());
                        newobject.setXClassReference(object.getRelativeXClassReference());
                        newobject.setDocumentReference(object.getDocumentReference());
                        newobject.setNumber(object.getNumber());
                        newobject.setGuid(object.getGuid());
                        object = newobject;
                    }
                    if (classReference.equals(groupsDocumentReference)) {
                        // Groups objects are handled differently.
                        hasGroups = true;
                    } else {
                        loadXWikiCollectionInternal(object, doc, context, false, true);
                    }
                    doc.setXObject(object.getNumber(), object);
                }
                // This will do every group member in a single query.
                if (hasGroups) {
                    Query query2 = session.createQuery("select bobject.number, prop.value from StringProperty as prop," + "BaseObject as bobject where bobject.name = :name and bobject.className='XWiki.XWikiGroups' " + "and bobject.id=prop.id.id and prop.id.name='member' order by bobject.number");
                    query2.setText("name", doc.getFullName());
                    @SuppressWarnings("unchecked") Iterator<Object[]> it2 = query2.list().iterator();
                    while (it2.hasNext()) {
                        Object[] result = it2.next();
                        Integer number = (Integer) result[0];
                        String member = (String) result[1];
                        BaseObject obj = BaseClass.newCustomClassInstance(groupsDocumentReference, context);
                        obj.setDocumentReference(doc.getDocumentReference());
                        obj.setXClassReference(localGroupEntityReference);
                        obj.setNumber(number.intValue());
                        obj.setStringValue("member", member);
                        doc.setXObject(obj.getNumber(), obj);
                    }
                }
            }
            doc.setContentDirty(false);
            doc.setMetaDataDirty(false);
            // We need to ensure that the loaded document becomes the original document
            doc.setOriginalDocument(doc.clone());
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
            Object[] args = { doc.getDocumentReference() };
            throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_READING_DOC, "Exception while reading document [{0}]", e, args);
        } finally {
            try {
                if (bTransaction) {
                    endTransaction(context, false);
                }
            } catch (Exception e) {
            }
            // End monitoring timer
            if (monitor != null) {
                monitor.endTimer(HINT);
            }
        }
        this.logger.debug("Loaded XWikiDocument: [{}]", doc.getDocumentReference());
        return doc;
    } finally {
        restoreExecutionXContext();
    }
}
Also used : SessionFactory(org.hibernate.SessionFactory) Query(org.hibernate.Query) MonitorPlugin(com.xpn.xwiki.monitor.api.MonitorPlugin) XWikiContext(com.xpn.xwiki.XWikiContext) 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) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) EntityReference(org.xwiki.model.reference.EntityReference) BaseObject(com.xpn.xwiki.objects.BaseObject) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException) Session(org.hibernate.Session)

Aggregations

BaseClass (com.xpn.xwiki.objects.classes.BaseClass)100 DocumentReference (org.xwiki.model.reference.DocumentReference)42 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)41 BaseObject (com.xpn.xwiki.objects.BaseObject)40 XWikiException (com.xpn.xwiki.XWikiException)26 XWikiContext (com.xpn.xwiki.XWikiContext)24 ArrayList (java.util.ArrayList)18 PropertyClass (com.xpn.xwiki.objects.classes.PropertyClass)16 XWiki (com.xpn.xwiki.XWiki)15 Test (org.junit.Test)15 LocalDocumentReference (org.xwiki.model.reference.LocalDocumentReference)15 EntityReference (org.xwiki.model.reference.EntityReference)10 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)9 BaseProperty (com.xpn.xwiki.objects.BaseProperty)9 List (java.util.List)9 ToString (org.suigeneris.jrcs.util.ToString)9 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)7 Before (org.junit.Before)6 TextAreaClass (com.xpn.xwiki.objects.classes.TextAreaClass)5 MigrationRequiredException (com.xpn.xwiki.store.migration.MigrationRequiredException)5