Search in sources :

Example 21 with ObservationManager

use of org.xwiki.observation.ObservationManager 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 22 with ObservationManager

use of org.xwiki.observation.ObservationManager in project xwiki-platform by xwiki.

the class DefaultWikiMacro method execute.

@Override
public List<Block> execute(WikiMacroParameters parameters, String macroContent, MacroTransformationContext context) throws MacroExecutionException {
    validate(parameters, macroContent);
    // Parse the wiki macro content.
    XDOM xdom = prepareWikiMacroContent(context);
    // Prepare macro context.
    Map<String, Object> macroBinding = new HashMap<>();
    macroBinding.put(MACRO_PARAMS_KEY, parameters);
    macroBinding.put(MACRO_CONTENT_KEY, macroContent);
    macroBinding.put(MACRO_DESCRIPTOR_KEY, getDescriptor());
    macroBinding.put(MACRO_CONTEXT_KEY, context);
    macroBinding.put(MACRO_RESULT_KEY, null);
    // Extension point to add more wiki macro bindings
    try {
        List<WikiMacroBindingInitializer> bindingInitializers = this.componentManager.getInstanceList(WikiMacroBindingInitializer.class);
        for (WikiMacroBindingInitializer bindingInitializer : bindingInitializers) {
            bindingInitializer.initialize(this.macroDocumentReference, parameters, macroContent, context, macroBinding);
        }
    } catch (ComponentLookupException e) {
    // TODO: we should probably log something but that should never happen
    }
    // Execute the macro
    ObservationManager observation = null;
    try {
        observation = this.componentManager.getInstance(ObservationManager.class);
    } catch (ComponentLookupException e) {
    // TODO: maybe log something
    }
    // Get XWiki context
    Map<String, Object> xwikiContext = null;
    try {
        Execution execution = this.componentManager.getInstance(Execution.class);
        ExecutionContext econtext = execution.getContext();
        if (econtext != null) {
            xwikiContext = (Map<String, Object>) execution.getContext().getProperty("xwikicontext");
        }
    } catch (ComponentLookupException e) {
    // TODO: maybe log something
    }
    try {
        Transformation macroTransformation = this.componentManager.getInstance(Transformation.class, MACRO_HINT);
        if (xwikiContext != null) {
            // Place macro context inside xwiki context ($xcontext.macro).
            xwikiContext.put(MACRO_KEY, macroBinding);
        }
        MacroBlock wikiMacroBlock = context.getCurrentMacroBlock();
        MacroMarkerBlock wikiMacroMarker = new MacroMarkerBlock(wikiMacroBlock.getId(), wikiMacroBlock.getParameters(), wikiMacroBlock.getContent(), xdom.getChildren(), wikiMacroBlock.isInline());
        // Make sure to use provided metadatas
        MetaDataBlock metaDataBlock = new MetaDataBlock(Collections.<Block>singletonList(wikiMacroMarker), xdom.getMetaData());
        // Make sure the context XDOM contains the wiki macro content
        wikiMacroBlock.getParent().replaceChild(metaDataBlock, wikiMacroBlock);
        // "Emulate" the fact that wiki macro block is still part of the XDOM (what is in the XDOM is a
        // MacroMarkerBlock and MacroTransformationContext current macro block only support MacroBlock so we can't
        // switch it without breaking some APIs)
        wikiMacroBlock.setParent(metaDataBlock.getParent());
        wikiMacroBlock.setNextSiblingBlock(metaDataBlock.getNextSibling());
        wikiMacroBlock.setPreviousSiblingBlock(metaDataBlock.getPreviousSibling());
        try {
            if (observation != null) {
                observation.notify(STARTEXECUTION_EVENT, this, macroBinding);
            }
            // Perform internal macro transformations.
            TransformationContext txContext = new TransformationContext(context.getXDOM(), this.syntax);
            txContext.setId(context.getId());
            RenderingContext renderingContext = componentManager.getInstance(RenderingContext.class);
            ((MutableRenderingContext) renderingContext).transformInContext(macroTransformation, txContext, wikiMacroMarker);
        } finally {
            // Restore context XDOM to its previous state
            metaDataBlock.getParent().replaceChild(wikiMacroBlock, metaDataBlock);
        }
        return extractResult(wikiMacroMarker.getChildren(), macroBinding, context);
    } catch (Exception ex) {
        throw new MacroExecutionException("Error while performing internal macro transformations", ex);
    } finally {
        if (xwikiContext != null) {
            xwikiContext.remove(MACRO_KEY);
        }
        if (observation != null) {
            observation.notify(ENDEXECUTION_EVENT, this);
        }
    }
}
Also used : RenderingContext(org.xwiki.rendering.transformation.RenderingContext) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext) Transformation(org.xwiki.rendering.transformation.Transformation) XDOM(org.xwiki.rendering.block.XDOM) HashMap(java.util.HashMap) MacroMarkerBlock(org.xwiki.rendering.block.MacroMarkerBlock) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) ObservationManager(org.xwiki.observation.ObservationManager) TransformationContext(org.xwiki.rendering.transformation.TransformationContext) MacroTransformationContext(org.xwiki.rendering.transformation.MacroTransformationContext) MacroExecutionException(org.xwiki.rendering.macro.MacroExecutionException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) MacroParameterException(org.xwiki.rendering.macro.parameter.MacroParameterException) Execution(org.xwiki.context.Execution) ExecutionContext(org.xwiki.context.ExecutionContext) MacroExecutionException(org.xwiki.rendering.macro.MacroExecutionException) MutableRenderingContext(org.xwiki.rendering.internal.transformation.MutableRenderingContext) MacroBlock(org.xwiki.rendering.block.MacroBlock) MetaDataBlock(org.xwiki.rendering.block.MetaDataBlock)

Example 23 with ObservationManager

use of org.xwiki.observation.ObservationManager in project xwiki-platform by xwiki.

the class XWikiServletContextListener method contextInitialized.

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    // Initializes the Embeddable Component Manager
    EmbeddableComponentManager ecm = new EmbeddableComponentManager();
    // Initialize all the components. Note that this can fail with a Runtime Exception. This is done voluntarily so
    // that the XWiki webapp will not be available if one component fails to load. It's better to fail-fast.
    ecm.initialize(this.getClass().getClassLoader());
    this.componentManager = ecm;
    // This is a temporary bridge to allow non XWiki components to lookup XWiki components.
    // We're putting the XWiki Component Manager instance in the Servlet Context so that it's
    // available in the XWikiAction class which in turn puts it into the XWikiContext instance.
    // Class that need to lookup then just need to get it from the XWikiContext instance.
    // This is of course not necessary for XWiki components since they just need to implement
    // the Composable interface to get access to the Component Manager or better they simply
    // need to declare their components requirements using the @Inject annotation of the xwiki
    // component manager together with a private class member, for automatic injection by the CM on init.
    servletContextEvent.getServletContext().setAttribute(org.xwiki.component.manager.ComponentManager.class.getName(), this.componentManager);
    // Use a Component Event Manager that stacks Component instance creation events till we tell it to flush them.
    // The reason is that the Observation Manager used to send the events but we need the Application Context to
    // be set up before we start sending events since there can be Observation Listener components that require
    // the Application Context (this is the case for example for the Office Importer Lifecycle Listener).
    StackingComponentEventManager eventManager = new StackingComponentEventManager();
    this.componentManager.setComponentEventManager(eventManager);
    // Initialize the Environment
    try {
        ServletEnvironment servletEnvironment = this.componentManager.getInstance(Environment.class);
        servletEnvironment.setServletContext(servletContextEvent.getServletContext());
    } catch (ComponentLookupException e) {
        throw new RuntimeException("Failed to initialize the Servlet Environment", e);
    }
    // below in an Event Listener and move it to the legacy module.
    try {
        ServletContainerInitializer containerInitializer = this.componentManager.getInstance(ServletContainerInitializer.class);
        containerInitializer.initializeApplicationContext(servletContextEvent.getServletContext());
    } catch (ComponentLookupException e) {
        throw new RuntimeException("Failed to initialize the Application Context", e);
    }
    // Send an Observation event to signal the XWiki application is started. This allows components who need to do
    // something on startup to do it.
    ObservationManager observationManager;
    try {
        observationManager = this.componentManager.getInstance(ObservationManager.class);
    } catch (ComponentLookupException e) {
        throw new RuntimeException("Failed to find the Observation Manager component", e);
    }
    // Now that the Application Context is set up, send the Component instance creation events we had stacked up.
    eventManager.setObservationManager(observationManager);
    eventManager.shouldStack(false);
    eventManager.flushEvents();
    // Make sure installed extensions are initialized before sending ApplicationStartedEvent
    try {
        this.componentManager.getInstance(ExtensionInitializer.class);
    } catch (ComponentLookupException e) {
        throw new RuntimeException("Failed to initialize installed extensions", e);
    }
    // Indicate to the various components that XWiki is ready
    observationManager.notify(new ApplicationStartedEvent(), this);
}
Also used : EmbeddableComponentManager(org.xwiki.component.embed.EmbeddableComponentManager) ApplicationStartedEvent(org.xwiki.observation.event.ApplicationStartedEvent) EmbeddableComponentManager(org.xwiki.component.embed.EmbeddableComponentManager) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) ObservationManager(org.xwiki.observation.ObservationManager) StackingComponentEventManager(org.xwiki.component.internal.StackingComponentEventManager) ServletEnvironment(org.xwiki.environment.internal.ServletEnvironment)

Example 24 with ObservationManager

use of org.xwiki.observation.ObservationManager in project xwiki-platform by xwiki.

the class AttachmentEventGeneratorListener method onDocumentDeletedEvent.

/**
 * @param originalDoc the previous version of the document
 * @param doc the new version of the document
 * @param context the XWiki context
 */
private void onDocumentDeletedEvent(XWikiDocument originalDoc, XWikiDocument doc, XWikiContext context) {
    ObservationManager observation = Utils.getComponent(ObservationManager.class);
    for (XWikiAttachment attachment : originalDoc.getAttachmentList()) {
        String reference = this.defaultEntityReferenceSerializer.serialize(attachment.getDoc().getDocumentReference());
        observation.notify(new AttachmentDeletedEvent(reference, attachment.getFilename()), doc, context);
    }
}
Also used : ObservationManager(org.xwiki.observation.ObservationManager) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment)

Example 25 with ObservationManager

use of org.xwiki.observation.ObservationManager in project xwiki-platform by xwiki.

the class AttachmentEventGeneratorListener method onDocumentCreatedEvent.

/**
 * @param originalDoc the previous version of the document
 * @param doc the new version of the document
 * @param context the XWiki context
 */
private void onDocumentCreatedEvent(XWikiDocument originalDoc, XWikiDocument doc, XWikiContext context) {
    ObservationManager observation = Utils.getComponent(ObservationManager.class);
    for (XWikiAttachment attachment : doc.getAttachmentList()) {
        String reference = this.defaultEntityReferenceSerializer.serialize(attachment.getDoc().getDocumentReference());
        observation.notify(new AttachmentAddedEvent(reference, attachment.getFilename()), doc, context);
    }
}
Also used : ObservationManager(org.xwiki.observation.ObservationManager) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment)

Aggregations

ObservationManager (org.xwiki.observation.ObservationManager)28 DocumentReference (org.xwiki.model.reference.DocumentReference)11 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)9 Test (org.junit.Test)7 ComponentLookupException (org.xwiki.component.manager.ComponentLookupException)6 DocumentDeletedEvent (org.xwiki.bridge.event.DocumentDeletedEvent)4 DocumentUpdatedEvent (org.xwiki.bridge.event.DocumentUpdatedEvent)4 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)3 ParseGroovyFromString (com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString)3 IncludeServletAsString (com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString)3 IOException (java.io.IOException)3 Date (java.util.Date)3 Mock (org.jmock.Mock)3 DocumentDeletingEvent (org.xwiki.bridge.event.DocumentDeletingEvent)3 XWikiAttachmentToRemove (com.xpn.xwiki.doc.XWikiDocument.XWikiAttachmentToRemove)2 XARImportedEvent (com.xpn.xwiki.internal.event.XARImportedEvent)2 XARImportingEvent (com.xpn.xwiki.internal.event.XARImportingEvent)2 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)2 FileNotFoundException (java.io.FileNotFoundException)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2