Search in sources :

Example 6 with MonitorPlugin

use of com.xpn.xwiki.monitor.api.MonitorPlugin 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)

Example 7 with MonitorPlugin

use of com.xpn.xwiki.monitor.api.MonitorPlugin 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 8 with MonitorPlugin

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

the class XWikiAction method execute.

public ActionForward execute(XWikiContext context) throws Exception {
    MonitorPlugin monitor = null;
    FileUploadPlugin fileupload = null;
    DefaultJobProgress actionProgress = null;
    ObservationManager om = Utils.getComponent(ObservationManager.class);
    Execution execution = Utils.getComponent(Execution.class);
    String docName = "";
    boolean debug = StringUtils.equals(context.getRequest().get("debug"), "true");
    try {
        String action = context.getAction();
        // Start progress
        if (debug && om != null && execution != null) {
            actionProgress = new DefaultJobProgress(context.getURL().toExternalForm());
            om.addListener(new WrappedThreadEventListener(actionProgress));
            // Register the action progress in the context
            ExecutionContext econtext = execution.getContext();
            if (econtext != null) {
                econtext.setProperty(XWikiAction.ACTION_PROGRESS, actionProgress);
            }
        }
        getProgress().pushLevelProgress(2, this);
        getProgress().startStep(this, "Get XWiki instance");
        // Initialize context.getWiki() with the main wiki
        XWiki xwiki;
        // Verify that the requested wiki exists
        try {
            xwiki = XWiki.getXWiki(this.waitForXWikiInitialization, context);
            // If XWiki is still initializing display initialization template
            if (xwiki == null) {
                // Display initialization template
                renderInit(context);
                // Initialization template has been displayed, stop here.
                return null;
            }
        } catch (XWikiException e) {
            // redirects. If there are none, then we display the specific error template.
            if (e.getCode() == XWikiException.ERROR_XWIKI_DOES_NOT_EXIST) {
                xwiki = XWiki.getMainXWiki(context);
                // Initialize the url factory
                XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);
                context.setURLFactory(urlf);
                // Initialize the velocity context and its bindings so that it may be used in the velocity templates
                // that we
                // are parsing below.
                VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
                VelocityContext vcontext = velocityManager.getVelocityContext();
                if (!sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {
                    // Starting XWiki 5.0M2, 'xwiki.virtual.redirect' was removed. Warn users still using it.
                    if (!StringUtils.isEmpty(context.getWiki().Param("xwiki.virtual.redirect"))) {
                        LOGGER.warn(String.format("%s %s", "'xwiki.virtual.redirect' is no longer supported.", "Please update your configuration and/or see XWIKI-8914 for more details."));
                    }
                    // Display the error template only for actions that are not ignored
                    if (!ACTIONS_IGNORED_WHEN_WIKI_DOES_NOT_EXIST.contains(action)) {
                        // Add localization resources to the context
                        xwiki.prepareResources(context);
                        // Set the main home page in the main space of the main wiki as the current requested entity
                        // since we cannot set the non existing one as it would generate errors obviously...
                        EntityReferenceValueProvider valueProvider = Utils.getComponent(EntityReferenceValueProvider.class);
                        xwiki.setPhonyDocument(new DocumentReference(valueProvider.getDefaultValue(EntityType.WIKI), valueProvider.getDefaultValue(EntityType.SPACE), valueProvider.getDefaultValue(EntityType.DOCUMENT)), context, vcontext);
                        // Parse the error template
                        Utils.parseTemplate(context.getWiki().Param("xwiki.wiki_exception", "wikidoesnotexist"), context);
                        // Error template was displayed, stop here.
                        return null;
                    }
                // At this point, we allow regular execution of the ignored action because even if the wiki
                // does not exist, we still need to allow UI resources to be retrieved (from the filesystem
                // and the main wiki) or our error template will not be rendered properly.
                // Proceed with serving the main wiki
                } else {
                    // Global redirect was executed, stop here.
                    return null;
                }
            } else {
                LOGGER.error("Uncaught exception during XWiki initialisation:", e);
                throw e;
            }
        }
        // Send global redirection (if any)
        if (sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {
            return null;
        }
        XWikiURLFactory urlf = xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);
        context.setURLFactory(urlf);
        // Handle ability to enter space URLs and convert them to page URLs (Nested Documents)
        if (redirectSpaceURLs(action, urlf, xwiki, context)) {
            return null;
        }
        String sajax = context.getRequest().get("ajax");
        boolean ajax = false;
        if (sajax != null && !sajax.trim().equals("") && !sajax.equals("0")) {
            ajax = true;
        }
        context.put("ajax", ajax);
        if (monitor != null) {
            monitor.startTimer("request");
        }
        getProgress().startStep(this, "Execute request");
        VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
        VelocityContext vcontext = velocityManager.getVelocityContext();
        getProgress().pushLevelProgress(7, this);
        boolean eventSent = false;
        try {
            getProgress().startStep(this, "Prepare documents and put them in the context");
            // Prepare documents and put them in the context
            if (!xwiki.prepareDocuments(context.getRequest(), context, vcontext)) {
                return null;
            }
            // Start monitoring timer
            monitor = (MonitorPlugin) xwiki.getPlugin("monitor", context);
            if (monitor != null) {
                monitor.startRequest("", context.getAction(), context.getURL());
                monitor.startTimer("multipart");
            }
            getProgress().startStep(this, "Parses multipart");
            // Parses multipart so that params in multipart are available for all actions
            fileupload = Utils.handleMultipart(context.getRequest().getHttpServletRequest(), context);
            if (monitor != null) {
                monitor.endTimer("multipart");
            }
            if (monitor != null) {
                monitor.setWikiPage(context.getDoc().getFullName());
            }
            getProgress().startStep(this, "Send [" + context.getAction() + "] action start event");
            // and there won't be a need for the context.
            try {
                ActionExecutingEvent event = new ActionExecutingEvent(context.getAction());
                om.notify(event, context.getDoc(), context);
                eventSent = true;
                if (event.isCanceled()) {
                    // TODO: do something special ?
                    return null;
                }
            } catch (Throwable ex) {
                LOGGER.error("Cannot send action notifications for document [" + context.getDoc() + " using action [" + context.getAction() + "]", ex);
            }
            if (monitor != null) {
                monitor.endTimer("prenotify");
            }
            // Call the Actions
            getProgress().startStep(this, "Search and execute entity resource handler");
            // Call the new Entity Resource Reference Handler.
            ResourceReferenceHandler entityResourceReferenceHandler = Utils.getComponent(new DefaultParameterizedType(null, ResourceReferenceHandler.class, ResourceType.class), "bin");
            ResourceReference resourceReference = Utils.getComponent(ResourceReferenceManager.class).getResourceReference();
            try {
                entityResourceReferenceHandler.handle(resourceReference, DefaultResourceReferenceHandlerChain.EMPTY);
                // Don't let the old actions kick in!
                return null;
            } catch (NotFoundResourceHandlerException e) {
            // No Entity Resource Action has been found. Don't do anything and let it go through
            // so that the old Action system kicks in...
            } catch (Throwable e) {
                // Some real failure, log it since it's a problem but still allow the old Action system a chance
                // to do something...
                LOGGER.error("Failed to handle Action for Resource [{}]", resourceReference, e);
            }
            getProgress().startStep(this, "Execute action render");
            // Handle the XWiki.RedirectClass object that can be attached to the current document
            boolean hasRedirect = false;
            if (handleRedirectObject) {
                hasRedirect = handleRedirectObject(context);
            }
            // Then call the old Actions for backward compatibility (and because a lot of them have not been
            // migrated to new Actions yet).
            String renderResult = null;
            XWikiDocument doc = context.getDoc();
            docName = doc.getFullName();
            if (!hasRedirect && action(context)) {
                renderResult = render(context);
            }
            if (renderResult != null) {
                if (doc.isNew() && "view".equals(context.getAction()) && !"recyclebin".equals(context.getRequest().get("viewer")) && !"children".equals(context.getRequest().get("viewer")) && !"siblings".equals(context.getRequest().get("viewer"))) {
                    String page = Utils.getPage(context.getRequest(), "docdoesnotexist");
                    getProgress().startStep(this, "Execute template [" + page + "]");
                    Utils.parseTemplate(page, context);
                } else {
                    String page = Utils.getPage(context.getRequest(), renderResult);
                    getProgress().startStep(this, "Execute template [" + page + "]");
                    Utils.parseTemplate(page, !page.equals("direct"), context);
                }
            }
            return null;
        } catch (Throwable e) {
            if (e instanceof IOException) {
                e = new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION, "Exception while sending response", e);
            }
            if (!(e instanceof XWikiException)) {
                e = new XWikiException(XWikiException.MODULE_XWIKI_APP, XWikiException.ERROR_XWIKI_UNKNOWN, "Uncaught exception", e);
            }
            try {
                XWikiException xex = (XWikiException) e;
                if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
                    // Connection aborted from the client side, there's not much we can do on the server side. We
                    // simply ignore it.
                    LOGGER.debug("Connection aborted", e);
                    // We don't write any other message to the response, as the connection is broken, anyway.
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_ACCESS_DENIED) {
                    Utils.parseTemplate(context.getWiki().Param("xwiki.access_exception", "accessdenied"), context);
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_USER_INACTIVE) {
                    Utils.parseTemplate(context.getWiki().Param("xwiki.user_exception", "userinactive"), context);
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_ATTACHMENT_NOT_FOUND) {
                    context.put("message", "attachmentdoesnotexist");
                    Utils.parseTemplate(context.getWiki().Param("xwiki.attachment_exception", "attachmentdoesnotexist"), context);
                    return null;
                } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION) {
                    vcontext.put("message", localizePlainOrKey("platform.core.invalidUrl"));
                    xwiki.setPhonyDocument(xwiki.getDefaultSpace(context) + "." + xwiki.getDefaultPage(context), context, vcontext);
                    context.getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    Utils.parseTemplate(context.getWiki().Param("xwiki.invalid_url_exception", "error"), context);
                    return null;
                }
                vcontext.put("exp", e);
                if (LOGGER.isWarnEnabled()) {
                    // connection.
                    if (ExceptionUtils.getRootCauseMessage(e).equals("IOException: Broken pipe")) {
                        return null;
                    }
                    LOGGER.warn("Uncaught exception: " + e.getMessage(), e);
                }
                // If the request is an AJAX request, we don't return a whole HTML page, but just the exception
                // inline.
                String exceptionTemplate = ajax ? "exceptioninline" : "exception";
                Utils.parseTemplate(Utils.getPage(context.getRequest(), exceptionTemplate), context);
                return null;
            } catch (XWikiException ex) {
                if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
                    LOGGER.error("Connection aborted");
                }
            } catch (Exception e2) {
                // I hope this never happens
                LOGGER.error("Uncaught exceptions (inner): ", e);
                LOGGER.error("Uncaught exceptions (outer): ", e2);
            }
            return null;
        } finally {
            // Let's make sure we have flushed content and closed
            try {
                context.getResponse().getWriter().flush();
            } catch (Throwable e) {
            // This might happen if the connection was closed, for example.
            // If we can't flush, then there's nothing more we can send to the client.
            }
            if (monitor != null) {
                monitor.endTimer("request");
                monitor.startTimer("notify");
            }
            if (eventSent) {
                // and there won't be a need for the context.
                try {
                    om.notify(new ActionExecutedEvent(context.getAction()), context.getDoc(), context);
                } catch (Throwable ex) {
                    LOGGER.error("Cannot send action notifications for document [" + docName + " using action [" + context.getAction() + "]", ex);
                }
            }
            if (monitor != null) {
                monitor.endTimer("notify");
            }
            getProgress().startStep(this, "Cleanup database connections");
            // Make sure we cleanup database connections
            // There could be cases where we have some
            xwiki.getStore().cleanUp(context);
            getProgress().popLevelProgress(this);
        }
    } finally {
        // End request
        if (monitor != null) {
            monitor.endRequest();
        }
        // Stop progress
        if (actionProgress != null) {
            getProgress().popLevelProgress(this);
            om.removeListener(actionProgress.getName());
        }
        if (fileupload != null) {
            fileupload.cleanFileList(context);
        }
    }
}
Also used : ResourceReferenceHandler(org.xwiki.resource.ResourceReferenceHandler) EntityReferenceValueProvider(org.xwiki.model.reference.EntityReferenceValueProvider) VelocityContext(org.apache.velocity.VelocityContext) ObservationManager(org.xwiki.observation.ObservationManager) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) FileUploadPlugin(com.xpn.xwiki.plugin.fileupload.FileUploadPlugin) Execution(org.xwiki.context.Execution) DefaultJobProgress(org.xwiki.job.internal.DefaultJobProgress) ActionExecutingEvent(org.xwiki.bridge.event.ActionExecutingEvent) ResourceReference(org.xwiki.resource.ResourceReference) EntityResourceReference(org.xwiki.resource.entity.EntityResourceReference) XWikiException(com.xpn.xwiki.XWikiException) DocumentReference(org.xwiki.model.reference.DocumentReference) MonitorPlugin(com.xpn.xwiki.monitor.api.MonitorPlugin) NotFoundResourceHandlerException(org.xwiki.resource.NotFoundResourceHandlerException) XWiki(com.xpn.xwiki.XWiki) ResourceType(org.xwiki.resource.ResourceType) IOException(java.io.IOException) WrappedThreadEventListener(org.xwiki.observation.WrappedThreadEventListener) XWikiException(com.xpn.xwiki.XWikiException) ServletException(javax.servlet.ServletException) ServletContainerException(org.xwiki.container.servlet.ServletContainerException) NotFoundResourceHandlerException(org.xwiki.resource.NotFoundResourceHandlerException) IOException(java.io.IOException) ExecutionContext(org.xwiki.context.ExecutionContext) VelocityManager(org.xwiki.velocity.VelocityManager) ActionExecutedEvent(org.xwiki.bridge.event.ActionExecutedEvent) ResourceReferenceManager(org.xwiki.resource.ResourceReferenceManager) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType)

Example 9 with MonitorPlugin

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

the class XWikiHibernateBaseStore method execute.

/**
 * Execute method for operations in hibernate. spring like.
 *
 * @param inputxcontext - used everywhere.
 * @param doCommit - should store commit changes(if any), or rollback it.
 * @param cb - callback to execute
 * @return {@link HibernateCallback#doInHibernate(Session)}
 * @throws XWikiException if any error
 */
public <T> T execute(XWikiContext inputxcontext, boolean doCommit, HibernateCallback<T> cb) throws XWikiException {
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    MonitorPlugin monitor = Util.getMonitorPlugin(context);
    boolean bTransaction = false;
    try {
        // Start monitoring timer
        if (monitor != null) {
            monitor.startTimer(XWikiHibernateBaseStore.HINT);
        }
        checkHibernate(context);
        bTransaction = beginTransaction(context);
        return cb.doInHibernate(this.store.getCurrentSession());
    } catch (Exception e) {
        doCommit = false;
        if (e instanceof XWikiException) {
            throw (XWikiException) e;
        }
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN, "Exception while hibernate execute", e);
    } finally {
        try {
            if (bTransaction) {
                this.store.endTransaction(doCommit);
            }
            if (monitor != null) {
                monitor.endTimer(XWikiHibernateBaseStore.HINT);
            }
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Exception while close transaction", e);
            }
        }
        restoreExecutionXContext();
    }
}
Also used : MonitorPlugin(com.xpn.xwiki.monitor.api.MonitorPlugin) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiException(com.xpn.xwiki.XWikiException) InitializationException(org.xwiki.component.phase.InitializationException) HibernateException(org.hibernate.HibernateException) XWikiException(com.xpn.xwiki.XWikiException)

Example 10 with MonitorPlugin

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

the class XWikiHibernateStore method searchDocuments.

@Override
public List<XWikiDocument> searchDocuments(String wheresql, boolean distinctbylanguage, boolean customMapping, boolean checkRight, int nb, int start, List<?> parameterValues, XWikiContext inputxcontext) throws XWikiException {
    XWikiContext context = getExecutionXContext(inputxcontext, true);
    // Search documents
    List documentDatas = new ArrayList();
    boolean bTransaction = true;
    MonitorPlugin monitor = Util.getMonitorPlugin(context);
    try {
        String sql;
        if (distinctbylanguage) {
            sql = createSQLQuery("select distinct doc.fullName, doc.language", wheresql);
        } else {
            sql = createSQLQuery("select distinct doc.fullName", wheresql);
        }
        // Start monitoring timer
        if (monitor != null) {
            monitor.startTimer(HINT, sql);
        }
        checkHibernate(context);
        if (bTransaction) {
            // Inject everything until we know what's needed
            SessionFactory sfactory = customMapping ? injectCustomMappingsInSessionFactory(context) : getSessionFactory();
            bTransaction = beginTransaction(sfactory, context);
        }
        Session session = getSession(context);
        Query query = session.createQuery(filterSQL(sql));
        injectParameterListToQuery(0, query, parameterValues);
        if (start != 0) {
            query.setFirstResult(start);
        }
        if (nb != 0) {
            query.setMaxResults(nb);
        }
        documentDatas.addAll(query.list());
        if (bTransaction) {
            endTransaction(context, false);
        }
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCH, "Exception while searching documents with SQL [{0}]", e, new Object[] { wheresql });
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }
        restoreExecutionXContext();
        // End monitoring timer
        if (monitor != null) {
            monitor.endTimer(HINT);
        }
    }
    // Resolve documents. We use two separated sessions because rights service could need to switch database to
    // check rights
    List<XWikiDocument> documents = new ArrayList<>();
    WikiReference currentWikiReference = new WikiReference(context.getWikiId());
    for (Object result : documentDatas) {
        String fullName;
        String locale = null;
        if (result instanceof String) {
            fullName = (String) result;
        } else {
            fullName = (String) ((Object[]) result)[0];
            if (distinctbylanguage) {
                locale = (String) ((Object[]) result)[1];
            }
        }
        XWikiDocument doc = new XWikiDocument(this.defaultDocumentReferenceResolver.resolve(fullName, currentWikiReference));
        if (checkRight) {
            if (!context.getWiki().getRightService().hasAccessLevel("view", context.getUser(), doc.getFullName(), context)) {
                continue;
            }
        }
        DocumentReference documentReference = doc.getDocumentReference();
        if (distinctbylanguage) {
            XWikiDocument document = context.getWiki().getDocument(documentReference, context);
            if (StringUtils.isEmpty(locale)) {
                documents.add(document);
            } else {
                documents.add(document.getTranslatedDocument(locale, context));
            }
        } else {
            documents.add(context.getWiki().getDocument(documentReference, context));
        }
    }
    return documents;
}
Also used : SessionFactory(org.hibernate.SessionFactory) Query(org.hibernate.Query) MonitorPlugin(com.xpn.xwiki.monitor.api.MonitorPlugin) 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) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) List(java.util.List) ArrayList(java.util.ArrayList) BaseObject(com.xpn.xwiki.objects.BaseObject) WikiReference(org.xwiki.model.reference.WikiReference) XWikiException(com.xpn.xwiki.XWikiException) DocumentReference(org.xwiki.model.reference.DocumentReference) Session(org.hibernate.Session)

Aggregations

XWikiException (com.xpn.xwiki.XWikiException)11 MonitorPlugin (com.xpn.xwiki.monitor.api.MonitorPlugin)11 InitializationException (org.xwiki.component.phase.InitializationException)10 XWikiContext (com.xpn.xwiki.XWikiContext)9 MigrationRequiredException (com.xpn.xwiki.store.migration.MigrationRequiredException)8 SQLException (java.sql.SQLException)8 ObjectNotFoundException (org.hibernate.ObjectNotFoundException)8 Session (org.hibernate.Session)8 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)8 QueryException (org.xwiki.query.QueryException)8 UnexpectedException (org.xwiki.store.UnexpectedException)8 BaseObject (com.xpn.xwiki.objects.BaseObject)6 Query (org.hibernate.Query)6 ArrayList (java.util.ArrayList)4 SessionFactory (org.hibernate.SessionFactory)4 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)3 List (java.util.List)3 DocumentReference (org.xwiki.model.reference.DocumentReference)3 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)2 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)2