Search in sources :

Example 76 with BaseClass

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

the class XWikiHibernateStore method saveXWikiCollection.

/**
 * @deprecated This is internal to XWikiHibernateStore and may be removed in the future.
 */
@Deprecated
public void saveXWikiCollection(BaseCollection object, XWikiContext inputxcontext, boolean bTransaction) throws XWikiException {
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    try {
        if (object == null) {
            return;
        }
        // We need a slightly different behavior here
        boolean stats = (object instanceof XWikiStats);
        if (!stats) {
            checkObjectClassIsLocal(object, context);
        }
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(context);
        }
        Session session = getSession(context);
        // Verify if the property already exists
        Query query;
        if (stats) {
            query = session.createQuery("select obj.id from " + object.getClass().getName() + " as obj where obj.id = :id");
        } else {
            query = session.createQuery("select obj.id from BaseObject as obj where obj.id = :id");
        }
        query.setLong("id", object.getId());
        if (query.uniqueResult() == null) {
            if (stats) {
                session.save(object);
            } else {
                session.save("com.xpn.xwiki.objects.BaseObject", object);
            }
        } else {
            if (stats) {
                session.update(object);
            } else {
                session.update("com.xpn.xwiki.objects.BaseObject", object);
            }
        }
        /*
             * if (stats) session.saveOrUpdate(object); else
             * session.saveOrUpdate((String)"com.xpn.xwiki.objects.BaseObject", (Object)object);
             */
        BaseClass bclass = object.getXClass(context);
        List<String> handledProps = new ArrayList<>();
        if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
            // save object using the custom mapping
            Map<String, Object> objmap = object.getCustomMappingMap();
            handledProps = bclass.getCustomMappingPropertyList(context);
            Session dynamicSession = session.getSession(EntityMode.MAP);
            query = session.createQuery("select obj.id from " + bclass.getName() + " as obj where obj.id = :id");
            query.setLong("id", object.getId());
            if (query.uniqueResult() == null) {
                dynamicSession.save(bclass.getName(), objmap);
            } else {
                dynamicSession.update(bclass.getName(), objmap);
            }
        // dynamicSession.saveOrUpdate((String) bclass.getName(), objmap);
        }
        if (object.getXClassReference() != null) {
            // Remove all existing properties
            if (object.getFieldsToRemove().size() > 0) {
                for (int i = 0; i < object.getFieldsToRemove().size(); i++) {
                    BaseProperty prop = (BaseProperty) object.getFieldsToRemove().get(i);
                    if (!handledProps.contains(prop.getName())) {
                        session.delete(prop);
                    }
                }
                object.setFieldsToRemove(new ArrayList<BaseProperty>());
            }
            Iterator<String> it = object.getPropertyList().iterator();
            while (it.hasNext()) {
                String key = it.next();
                BaseProperty prop = (BaseProperty) object.getField(key);
                if (!prop.getName().equals(key)) {
                    Object[] args = { key, object.getName() };
                    throw new XWikiException(XWikiException.MODULE_XWIKI_CLASSES, XWikiException.ERROR_XWIKI_CLASSES_FIELD_INVALID, "Field {0} in object {1} has an invalid name", null, args);
                }
                String pname = prop.getName();
                if (pname != null && !pname.trim().equals("") && !handledProps.contains(pname)) {
                    saveXWikiPropertyInternal(prop, context, false);
                }
            }
        }
        if (bTransaction) {
            endTransaction(context, true);
        }
    } catch (XWikiException xe) {
        throw xe;
    } catch (Exception e) {
        Object[] args = { object.getName() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_OBJECT, "Exception while saving object {0}", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, true);
            }
        } catch (Exception e) {
        }
        restoreExecutionXContext();
    }
}
Also used : Query(org.hibernate.Query) ArrayList(java.util.ArrayList) XWikiContext(com.xpn.xwiki.XWikiContext) 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) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) BaseObject(com.xpn.xwiki.objects.BaseObject) XWikiStats(com.xpn.xwiki.stats.impl.XWikiStats) BaseProperty(com.xpn.xwiki.objects.BaseProperty) XWikiException(com.xpn.xwiki.XWikiException) Session(org.hibernate.Session)

Example 77 with BaseClass

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

the class XWikiHibernateStore method loadXWikiCollectionInternal.

private void loadXWikiCollectionInternal(BaseCollection object1, XWikiDocument doc, XWikiContext inputxcontext, boolean bTransaction, boolean alreadyLoaded) throws XWikiException {
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    BaseCollection object = object1;
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(false, context);
        }
        Session session = getSession(context);
        if (!alreadyLoaded) {
            try {
                session.load(object, object1.getId());
            } catch (ObjectNotFoundException e) {
                // There is no object data saved
                object = null;
                return;
            }
        }
        DocumentReference classReference = object.getXClassReference();
        // If the class reference is null in the loaded object then skip loading properties
        if (classReference != null) {
            BaseClass bclass = null;
            if (!classReference.equals(object.getDocumentReference())) {
                // Let's check if the class has a custom mapping
                bclass = object.getXClass(context);
            } else {
                // we will go in an endless loop
                if (doc != null) {
                    bclass = doc.getXClass();
                }
            }
            List<String> handledProps = new ArrayList<String>();
            try {
                if ((bclass != null) && (bclass.hasCustomMapping()) && context.getWiki().hasCustomMappings()) {
                    Session dynamicSession = session.getSession(EntityMode.MAP);
                    Object map = dynamicSession.load(bclass.getName(), object.getId());
                    // Let's make sure to look for null fields in the dynamic mapping
                    bclass.fromValueMap((Map) map, object);
                    handledProps = bclass.getCustomMappingPropertyList(context);
                    for (String prop : handledProps) {
                        if (((Map) map).get(prop) == null) {
                            handledProps.remove(prop);
                        }
                    }
                }
            } catch (Exception e) {
            }
            // Load strings, integers, dates all at once
            Query query = session.createQuery("select prop.name, prop.classType from BaseProperty as prop where prop.id.id = :id");
            query.setLong("id", object.getId());
            for (Object[] result : (List<Object[]>) query.list()) {
                String name = (String) result[0];
                // custom mapping
                if (handledProps.contains(name)) {
                    continue;
                }
                String classType = (String) result[1];
                BaseProperty property = null;
                try {
                    property = (BaseProperty) Class.forName(classType).newInstance();
                    property.setObject(object);
                    property.setName(name);
                    loadXWikiProperty(property, context, false);
                } catch (Exception e) {
                    // WORKAROUND IN CASE OF MIXMATCH BETWEEN STRING AND LARGESTRING
                    try {
                        if (property instanceof StringProperty) {
                            LargeStringProperty property2 = new LargeStringProperty();
                            property2.setObject(object);
                            property2.setName(name);
                            loadXWikiProperty(property2, context, false);
                            property.setValue(property2.getValue());
                            if (bclass != null) {
                                if (bclass.get(name) instanceof TextAreaClass) {
                                    property = property2;
                                }
                            }
                        } else if (property instanceof LargeStringProperty) {
                            StringProperty property2 = new StringProperty();
                            property2.setObject(object);
                            property2.setName(name);
                            loadXWikiProperty(property2, context, false);
                            property.setValue(property2.getValue());
                            if (bclass != null) {
                                if (bclass.get(name) instanceof StringClass) {
                                    property = property2;
                                }
                            }
                        } else {
                            throw e;
                        }
                    } catch (Throwable e2) {
                        Object[] args = { object.getName(), object.getClass(), Integer.valueOf(object.getNumber() + ""), name };
                        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT, "Exception while loading object '{0}' of class '{1}', number '{2}' and property '{3}'", e, args);
                    }
                }
                object.addField(name, property);
            }
        }
        if (bTransaction) {
            endTransaction(context, false, false);
        }
    } catch (Exception e) {
        Object[] args = { object.getName(), object.getClass(), Integer.valueOf(object.getNumber() + "") };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT, "Exception while loading object '{0}' of class '{1}' and number '{2}'", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false, false);
            }
        } catch (Exception e) {
        }
        restoreExecutionXContext();
    }
}
Also used : Query(org.hibernate.Query) ArrayList(java.util.ArrayList) XWikiContext(com.xpn.xwiki.XWikiContext) LargeStringProperty(com.xpn.xwiki.objects.LargeStringProperty) StringProperty(com.xpn.xwiki.objects.StringProperty) BaseStringProperty(com.xpn.xwiki.objects.BaseStringProperty) BaseCollection(com.xpn.xwiki.objects.BaseCollection) TextAreaClass(com.xpn.xwiki.objects.classes.TextAreaClass) 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) LargeStringProperty(com.xpn.xwiki.objects.LargeStringProperty) StringClass(com.xpn.xwiki.objects.classes.StringClass) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) BaseObject(com.xpn.xwiki.objects.BaseObject) List(java.util.List) ArrayList(java.util.ArrayList) BaseProperty(com.xpn.xwiki.objects.BaseProperty) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiException(com.xpn.xwiki.XWikiException) Session(org.hibernate.Session)

Example 78 with BaseClass

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

the class Package method install.

public int install(XWikiContext context) throws XWikiException {
    boolean isAdmin = context.getWiki().getRightService().hasWikiAdminRights(context);
    if (testInstall(isAdmin, context) == DocumentInfo.INSTALL_IMPOSSIBLE) {
        setStatus(DocumentInfo.INSTALL_IMPOSSIBLE, context);
        return DocumentInfo.INSTALL_IMPOSSIBLE;
    }
    boolean hasCustomMappings = false;
    for (DocumentInfo docinfo : this.customMappingFiles) {
        BaseClass bclass = docinfo.getDoc().getXClass();
        hasCustomMappings |= context.getWiki().getStore().injectCustomMapping(bclass, context);
    }
    if (hasCustomMappings) {
        context.getWiki().getStore().injectUpdatedCustomMappings(context);
    }
    int status = DocumentInfo.INSTALL_OK;
    // Determine if the user performing the installation is a farm admin.
    // We allow author preservation from the package only to farm admins.
    // In order to prevent sub-wiki admins to take control of a farm with forged packages.
    // We test it once for the whole import in case one of the document break user during the import process.
    boolean backup = this.backupPack && isFarmAdmin(context);
    // Notify all the listeners about import
    ObservationManager om = Utils.getComponent(ObservationManager.class);
    // FIXME: should be able to pass some sort of source here, the name of the attachment or the list of
    // imported documents. But for the moment it's fine
    om.notify(new XARImportingEvent(), null, context);
    try {
        // definitions are available when installing documents using them.
        for (DocumentInfo classFile : this.classFiles) {
            if (installDocument(classFile, isAdmin, backup, context) == DocumentInfo.INSTALL_ERROR) {
                status = DocumentInfo.INSTALL_ERROR;
            }
        }
        // Install the remaining documents (without class definitions).
        for (DocumentInfo docInfo : this.files) {
            if (!this.classFiles.contains(docInfo)) {
                if (installDocument(docInfo, isAdmin, backup, context) == DocumentInfo.INSTALL_ERROR) {
                    status = DocumentInfo.INSTALL_ERROR;
                }
            }
        }
        setStatus(status, context);
    } finally {
        // FIXME: should be able to pass some sort of source here, the name of the attachment or the list of
        // imported documents. But for the moment it's fine
        om.notify(new XARImportedEvent(), null, context);
        registerExtension(context);
    }
    return status;
}
Also used : XARImportingEvent(com.xpn.xwiki.internal.event.XARImportingEvent) XARImportedEvent(com.xpn.xwiki.internal.event.XARImportedEvent) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) ObservationManager(org.xwiki.observation.ObservationManager)

Example 79 with BaseClass

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

the class Package method add.

public boolean add(XWikiDocument doc, int defaultAction, XWikiContext context) throws XWikiException {
    if (!context.getWiki().checkAccess("edit", doc, context)) {
        return false;
    }
    for (int i = 0; i < this.files.size(); i++) {
        DocumentInfo di = this.files.get(i);
        if (di.getFullName().equals(doc.getFullName()) && (di.getLanguage().equals(doc.getLanguage()))) {
            if (defaultAction != DocumentInfo.ACTION_NOT_DEFINED) {
                di.setAction(defaultAction);
            }
            if (!doc.isNew()) {
                di.setDoc(doc);
            }
            return true;
        }
    }
    doc = doc.clone();
    try {
        filter(doc, context);
        DocumentInfo docinfo = new DocumentInfo(doc);
        docinfo.setAction(defaultAction);
        this.files.add(docinfo);
        BaseClass bclass = doc.getXClass();
        if (bclass.getFieldList().size() > 0) {
            this.classFiles.add(docinfo);
        }
        if (bclass.getCustomMapping() != null) {
            this.customMappingFiles.add(docinfo);
        }
        return true;
    } catch (ExcludeDocumentException e) {
        LOGGER.info("Skip the document " + doc.getDocumentReference());
        return false;
    }
}
Also used : BaseClass(com.xpn.xwiki.objects.classes.BaseClass)

Example 80 with BaseClass

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

the class XWikiDocumentLocaleEventGenerator method writeRevision.

private void writeRevision(XWikiDocument document, Object filter, XWikiDocumentFilter documentFilter, DocumentInstanceInputProperties properties) throws FilterException {
    // > WikiDocumentRevision
    FilterEventParameters revisionParameters = new FilterEventParameters();
    if (document.getRelativeParentReference() != null) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_PARENT, document.getRelativeParentReference());
    }
    revisionParameters.put(WikiDocumentFilter.PARAMETER_TITLE, document.getTitle());
    if (!document.getCustomClass().isEmpty()) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_CUSTOMCLASS, document.getCustomClass());
    }
    if (!document.getDefaultTemplate().isEmpty()) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_DEFAULTTEMPLATE, document.getDefaultTemplate());
    }
    if (!document.getValidationScript().isEmpty()) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_VALIDATIONSCRIPT, document.getValidationScript());
    }
    revisionParameters.put(WikiDocumentFilter.PARAMETER_SYNTAX, document.getSyntax());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_HIDDEN, document.isHidden());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_AUTHOR, document.getAuthor());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_COMMENT, document.getComment());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_DATE, document.getDate());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_MINOR, document.isMinorEdit());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT_AUTHOR, document.getContentAuthor());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT_DATE, document.getContentUpdateDate());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT, document.getContent());
    if (properties.isWithWikiDocumentContentHTML()) {
        try {
            XWikiContext xcontext = this.xcontextProvider.get();
            revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT_HTML, document.getRenderedContent(xcontext));
        } catch (XWikiException e) {
            this.logger.error("Failed to render content of document [{}] as HTML", document.getDocumentReference(), e);
        }
    }
    documentFilter.beginWikiDocumentRevision(document.getVersion(), revisionParameters);
    if (properties.isWithWikiAttachments()) {
        List<XWikiAttachment> sortedAttachments = new ArrayList<XWikiAttachment>(document.getAttachmentList());
        Collections.sort(sortedAttachments, new Comparator<XWikiAttachment>() {

            @Override
            public int compare(XWikiAttachment attachement1, XWikiAttachment attachement2) {
                if (attachement1 == null || attachement2 == null) {
                    int result = 0;
                    if (attachement1 != null) {
                        result = -1;
                    } else if (attachement2 != null) {
                        result = 1;
                    }
                    return result;
                }
                return attachement1.getFilename().compareTo(attachement2.getFilename());
            }
        });
        for (XWikiAttachment attachment : sortedAttachments) {
            ((XWikiAttachmentEventGenerator) this.attachmentEventGenerator).write(attachment, filter, documentFilter, properties);
        }
    }
    // Document Class
    if (properties.isWithWikiClass()) {
        BaseClass xclass = document.getXClass();
        if (!xclass.getFieldList().isEmpty()) {
            ((BaseClassEventGenerator) this.classEventGenerator).write(xclass, filter, documentFilter, properties);
        }
    }
    // Objects (THEIR ORDER IS MOLDED IN STONE!)
    if (properties.isWithWikiObjects()) {
        for (List<BaseObject> xobjects : document.getXObjects().values()) {
            for (BaseObject xobject : xobjects) {
                if (xobject != null) {
                    ((BaseObjectEventGenerator) this.objectEventGenerator).write(xobject, filter, documentFilter, properties);
                }
            }
        }
    }
    // < WikiDocumentRevision
    documentFilter.endWikiDocumentRevision(document.getVersion(), revisionParameters);
}
Also used : ArrayList(java.util.ArrayList) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) BaseObject(com.xpn.xwiki.objects.BaseObject) FilterEventParameters(org.xwiki.filter.FilterEventParameters) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) XWikiException(com.xpn.xwiki.XWikiException)

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