Search in sources :

Example 76 with BaseProperty

use of com.xpn.xwiki.objects.BaseProperty 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 77 with BaseProperty

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

the class XWikiHibernateStore method saveXWikiPropertyInternal.

private void saveXWikiPropertyInternal(final PropertyInterface property, final XWikiContext context, final boolean runInOwnTransaction) throws XWikiException {
    // Clone runInOwnTransaction so the value passed is not altered.
    boolean bTransaction = runInOwnTransaction;
    try {
        if (bTransaction) {
            this.checkHibernate(context);
            bTransaction = this.beginTransaction(context);
        }
        final Session session = this.getSession(context);
        Query query = session.createQuery("select prop.classType from BaseProperty as prop " + "where prop.id.id = :id and prop.id.name= :name");
        query.setLong("id", property.getId());
        query.setString("name", property.getName());
        String oldClassType = (String) query.uniqueResult();
        String newClassType = ((BaseProperty) property).getClassType();
        if (oldClassType == null) {
            session.save(property);
        } else if (oldClassType.equals(newClassType)) {
            session.update(property);
        } else {
            // The property type has changed. We cannot simply update its value because the new value and the old
            // value are stored in different tables (we're using joined-subclass to map different property types).
            // We must delete the old property value before saving the new one and for this we must load the old
            // property from the table that corresponds to the old property type (we cannot delete and save the new
            // property or delete a clone of the new property; loading the old property from the BaseProperty table
            // doesn't work either).
            query = session.createQuery("select prop from " + oldClassType + " as prop where prop.id.id = :id and prop.id.name= :name");
            query.setLong("id", property.getId());
            query.setString("name", property.getName());
            session.delete(query.uniqueResult());
            session.save(property);
        }
        ((BaseProperty) property).setValueDirty(false);
        if (bTransaction) {
            endTransaction(context, true);
        }
    } catch (Exception e) {
        // Something went wrong, collect some information.
        final BaseCollection obj = property.getObject();
        final Object[] args = { (obj != null) ? obj.getName() : "unknown", property.getName() };
        // Try to roll back the transaction if this is in it's own transaction.
        try {
            if (bTransaction) {
                this.endTransaction(context, false);
            }
        } catch (Exception ee) {
        // Not a lot we can do here if there was an exception committing and an exception rolling back.
        }
        // Throw the exception.
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT, "Exception while saving property {1} of object {0}", e, args);
    }
}
Also used : Query(org.hibernate.Query) BaseProperty(com.xpn.xwiki.objects.BaseProperty) BaseCollection(com.xpn.xwiki.objects.BaseCollection) 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 78 with BaseProperty

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

the class XWikiHibernateStore method loadXWikiProperty.

private void loadXWikiProperty(PropertyInterface property, XWikiContext context, boolean bTransaction) throws XWikiException {
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(false, context);
        }
        Session session = getSession(context);
        try {
            session.load(property, (Serializable) property);
            // safe to assume that a retrieved NULL value should actually be an empty string.
            if (property instanceof BaseStringProperty) {
                BaseStringProperty stringProperty = (BaseStringProperty) property;
                if (stringProperty.getValue() == null) {
                    stringProperty.setValue("");
                }
            }
            ((BaseProperty) property).setValueDirty(false);
        } catch (ObjectNotFoundException e) {
            // Let's accept that there is no data in property tables but log it
            this.logger.error("No data for property [{}] of object id [{}]", property.getName(), property.getId());
        }
        // Without this test ViewEditTest.testUpdateAdvanceObjectProp fails
        if (property instanceof ListProperty) {
            ((ListProperty) property).getList();
        }
        if (bTransaction) {
            endTransaction(context, false, false);
        }
    } catch (Exception e) {
        BaseCollection obj = property.getObject();
        Object[] args = { (obj != null) ? obj.getName() : "unknown", property.getName() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_OBJECT, "Exception while loading property {1} of object {0}", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false, false);
            }
        } catch (Exception e) {
        }
    }
}
Also used : ListProperty(com.xpn.xwiki.objects.ListProperty) BaseStringProperty(com.xpn.xwiki.objects.BaseStringProperty) ObjectNotFoundException(org.hibernate.ObjectNotFoundException) BaseProperty(com.xpn.xwiki.objects.BaseProperty) BaseCollection(com.xpn.xwiki.objects.BaseCollection) 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 79 with BaseProperty

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

the class PropertyClassEventGenerator method write.

@Override
public void write(PropertyClass xclassProperty, Object filter, PropertyClassFilter propertyFilter, DocumentInstanceInputProperties properties) throws FilterException {
    // > WikiClassProperty
    FilterEventParameters propertyParameters = FilterEventParameters.EMPTY;
    String classType = xclassProperty.getClassType();
    if (xclassProperty.getClass().getSimpleName().equals(classType + "Class")) {
        // Keep exporting the full Java class name for old/default property types to avoid breaking the XAR format
        // (to allow XClasses created with the current version of XWiki to be imported in an older version).
        classType = xclassProperty.getClass().getName();
    }
    propertyFilter.beginWikiClassProperty(xclassProperty.getName(), classType, propertyParameters);
    // * WikiClassPropertyField
    // Iterate over values sorted by field name so that the values are
    // exported to XML in a consistent order.
    Iterator<BaseProperty<?>> it = xclassProperty.getSortedIterator();
    while (it.hasNext()) {
        BaseProperty<?> bprop = it.next();
        propertyFilter.onWikiClassPropertyField(bprop.getName(), bprop.toText(), FilterEventParameters.EMPTY);
    }
    // < WikiClassProperty
    propertyFilter.endWikiClassProperty(xclassProperty.getName(), classType, propertyParameters);
}
Also used : FilterEventParameters(org.xwiki.filter.FilterEventParameters) BaseProperty(com.xpn.xwiki.objects.BaseProperty)

Example 80 with BaseProperty

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

the class CommentAddAction method action.

@Override
public boolean action(XWikiContext context) throws XWikiException {
    // CSRF prevention
    if (!csrfTokenCheck(context)) {
        return false;
    }
    XWiki xwiki = context.getWiki();
    XWikiResponse response = context.getResponse();
    XWikiDocument doc = context.getDoc();
    ObjectAddForm oform = (ObjectAddForm) context.getForm();
    // Make sure this class exists
    BaseClass baseclass = xwiki.getCommentsClass(context);
    if (doc.isNew()) {
        return true;
    } else if (context.getUser().equals(XWikiRightService.GUEST_USER_FULLNAME) && !checkCaptcha(context)) {
        getCurrentScriptContext().setAttribute("captchaAnswerWrong", Boolean.TRUE, ScriptContext.ENGINE_SCOPE);
    } else {
        // className = XWiki.XWikiComments
        String className = baseclass.getName();
        // Create a new comment object and mark the document as dirty.
        BaseObject object = doc.newObject(className, context);
        // TODO The map should be pre-filled with empty strings for all class properties, just like in
        // ObjectAddAction, so that properties missing from the request are still added to the database.
        baseclass.fromMap(oform.getObject(className), object);
        // Comment author checks
        if (XWikiRightService.GUEST_USER_FULLNAME.equals(context.getUser())) {
            // Guests should not be allowed to enter names that look like real XWiki user names.
            String author = ((BaseProperty) object.get(AUTHOR_PROPERTY_NAME)).getValue() + "";
            author = StringUtils.remove(author, ':');
            while (author.startsWith(USER_SPACE_PREFIX)) {
                author = StringUtils.removeStart(author, USER_SPACE_PREFIX);
            }
            // We need to make sure the author will fit in a String property, this is mostly a protection against
            // spammers who try to put large texts in this field
            author = author.substring(0, Math.min(author.length(), 255));
            object.set(AUTHOR_PROPERTY_NAME, author, context);
        } else {
            // A registered user must always post with his name.
            object.set(AUTHOR_PROPERTY_NAME, context.getUser(), context);
        }
        doc.setAuthorReference(context.getUserReference());
        // Save the new comment.
        xwiki.saveDocument(doc, localizePlainOrKey("core.comment.addComment"), true, context);
    }
    // If xpage is specified then allow the specified template to be parsed.
    if (context.getRequest().get("xpage") != null) {
        return true;
    }
    // forward to edit
    String redirect = Utils.getRedirect("edit", context);
    sendRedirect(response, redirect);
    return false;
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) XWiki(com.xpn.xwiki.XWiki) BaseProperty(com.xpn.xwiki.objects.BaseProperty) BaseObject(com.xpn.xwiki.objects.BaseObject)

Aggregations

BaseProperty (com.xpn.xwiki.objects.BaseProperty)87 BaseObject (com.xpn.xwiki.objects.BaseObject)26 ArrayList (java.util.ArrayList)16 XWikiException (com.xpn.xwiki.XWikiException)14 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)12 XMLAttributeValueFilter (com.xpn.xwiki.internal.xml.XMLAttributeValueFilter)12 org.apache.ecs.xhtml.input (org.apache.ecs.xhtml.input)11 XWikiContext (com.xpn.xwiki.XWikiContext)10 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)9 DocumentReference (org.xwiki.model.reference.DocumentReference)9 StringProperty (com.xpn.xwiki.objects.StringProperty)8 ListProperty (com.xpn.xwiki.objects.ListProperty)7 XWiki (com.xpn.xwiki.XWiki)5 BaseCollection (com.xpn.xwiki.objects.BaseCollection)5 LargeStringProperty (com.xpn.xwiki.objects.LargeStringProperty)5 List (java.util.List)5 Test (org.junit.Test)5 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)5 DBStringListProperty (com.xpn.xwiki.objects.DBStringListProperty)4 PropertyClass (com.xpn.xwiki.objects.classes.PropertyClass)4