Search in sources :

Example 1 with ObservationManager

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

the class LocalEventListener method onEvent.

@Override
public void onEvent(Event event, Object source, Object data) {
    if (this.remoteObservationManager == null) {
        try {
            // Make sure to not receive events until RemoteObservationManager is ready
            ObservationManager om = this.componentManager.getInstance(ObservationManager.class);
            om.removeListener(getName());
            this.remoteObservationManager = this.componentManager.getInstance(RemoteObservationManager.class);
            om.addListener(this);
            this.remoteObservationManager.notify(new LocalEventData(event, source, data));
        } catch (ComponentLookupException e) {
            this.logger.error("Failed to initialize the Remote Observation Manager", e);
        }
    } else {
        this.remoteObservationManager.notify(new LocalEventData(event, source, data));
    }
}
Also used : LocalEventData(org.xwiki.observation.remote.LocalEventData) ObservationManager(org.xwiki.observation.ObservationManager) RemoteObservationManager(org.xwiki.observation.remote.RemoteObservationManager) RemoteObservationManager(org.xwiki.observation.remote.RemoteObservationManager) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException)

Example 2 with ObservationManager

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

the class ImportAction method importPackageFilterStream.

private void importPackageFilterStream(XWikiAttachment packFile, XWikiRequest request, XWikiContext context) throws IOException, XWikiException, FilterException {
    String[] pages = request.getParameterValues("pages");
    XARInputProperties xarProperties = new XARInputProperties();
    DocumentInstanceOutputProperties instanceProperties = new DocumentInstanceOutputProperties();
    instanceProperties.setSaveComment("Imported from XAR");
    if (pages != null) {
        EntityReferenceSet entities = new EntityReferenceSet();
        EntityReferenceResolver<String> resolver = Utils.getComponent(EntityReferenceResolver.TYPE_STRING, "relative");
        for (String pageEntry : pages) {
            if (StringUtils.isNotEmpty(pageEntry)) {
                String locale = getLocale(pageEntry, request);
                int iAction = getAction(pageEntry, locale, request);
                String documentReference = getDocumentReference(pageEntry);
                if (iAction == DocumentInfo.ACTION_OVERWRITE) {
                    entities.includes(new LocalDocumentReference(resolver.resolve(documentReference, EntityType.DOCUMENT), LocaleUtils.toLocale(locale)));
                }
            }
        }
        xarProperties.setEntities(entities);
    }
    // Set the appropriate strategy to handle versions
    if (StringUtils.equals(request.getParameter("historyStrategy"), "reset")) {
        instanceProperties.setPreviousDeleted(true);
        instanceProperties.setVersionPreserved(false);
        xarProperties.setWithHistory(false);
    } else if (StringUtils.equals(request.getParameter("historyStrategy"), "replace")) {
        instanceProperties.setPreviousDeleted(true);
        instanceProperties.setVersionPreserved(true);
        xarProperties.setWithHistory(true);
    } else {
        instanceProperties.setPreviousDeleted(false);
        instanceProperties.setVersionPreserved(false);
        xarProperties.setWithHistory(false);
    }
    // Set the backup pack option
    if (StringUtils.equals(request.getParameter("importAsBackup"), "true")) {
        instanceProperties.setAuthorPreserved(true);
    } else {
        instanceProperties.setAuthorPreserved(false);
    }
    BeanInputFilterStreamFactory<XARInputProperties> xarFilterStreamFactory = Utils.getComponent((Type) InputFilterStreamFactory.class, FilterStreamType.XWIKI_XAR_CURRENT.serialize());
    BeanInputFilterStream<XARInputProperties> xarFilterStream = xarFilterStreamFactory.createInputFilterStream(xarProperties);
    BeanOutputFilterStreamFactory<InstanceOutputProperties> instanceFilterStreamFactory = Utils.getComponent((Type) OutputFilterStreamFactory.class, FilterStreamType.XWIKI_INSTANCE.serialize());
    BeanOutputFilterStream<InstanceOutputProperties> instanceFilterStream = instanceFilterStreamFactory.createOutputFilterStream(instanceProperties);
    // Notify all the listeners about import
    ObservationManager observation = Utils.getComponent(ObservationManager.class);
    InputStream source = packFile.getContentInputStream(context);
    xarProperties.setSource(new DefaultInputStreamInputSource(source));
    // Setup log
    xarProperties.setVerbose(true);
    instanceProperties.setVerbose(true);
    instanceProperties.setStoppedWhenSaveFail(false);
    LoggerManager loggerManager = Utils.getComponent(LoggerManager.class);
    LogQueue logger = new LogQueue();
    if (loggerManager != null) {
        // Isolate log
        loggerManager.pushLogListener(new LoggerListener(UUID.randomUUID().toString(), logger));
    }
    observation.notify(new XARImportingEvent(), null, context);
    try {
        xarFilterStream.read(instanceFilterStream.getFilter());
        xarFilterStream.close();
        instanceFilterStream.close();
    } finally {
        if (loggerManager != null) {
            // Stop isolating log
            loggerManager.popLogListener();
        }
        // Print the import log
        if (LOGGER.isDebugEnabled()) {
            logger.log(LOGGER);
        } else {
            // TODO: remove when the UI show the log properly
            for (LogEvent logEvent : logger.getLogsFrom(LogLevel.ERROR)) {
                logEvent.log(LOGGER);
            }
        }
        // Close the input source
        source.close();
        observation.notify(new XARImportedEvent(), null, context);
    }
    // Generate import report
    // Emulate old packager report (for retro compatibility)
    Package oldImporter = new Package();
    if (logger.containLogsFrom(LogLevel.ERROR)) {
        context.put("install_status", DocumentInfo.INSTALL_ERROR);
    } else {
        context.put("install_status", DocumentInfo.INSTALL_OK);
    }
    EntityReferenceSerializer<String> serializer = Utils.getComponent(EntityReferenceSerializer.TYPE_STRING, "local");
    for (LogEvent log : logger) {
        Marker marker = log.getMarker();
        if (marker != null) {
            if (marker.contains(WikiDocumentFilter.LOG_DOCUMENT_CREATED.getName()) || marker.contains(WikiDocumentFilter.LOG_DOCUMENT_UPDATED.getName())) {
                oldImporter.getInstalled(context).add(serializer.serialize((EntityReference) log.getArgumentArray()[0]));
            } else if (marker.contains(WikiDocumentFilter.LOG_DOCUMENT_SKIPPED.getName())) {
                oldImporter.getSkipped(context).add(serializer.serialize((EntityReference) log.getArgumentArray()[0]));
            } else if (marker.contains(WikiDocumentFilter.LOG_DOCUMENT_ERROR.getName())) {
                Object entity = log.getArgumentArray()[0];
                if (entity != null) {
                    oldImporter.getErrors(context).add(entity instanceof EntityReference ? serializer.serialize((EntityReference) log.getArgumentArray()[0]) : entity.toString());
                }
            }
        }
    }
}
Also used : InstanceOutputProperties(org.xwiki.filter.instance.output.InstanceOutputProperties) DocumentInstanceOutputProperties(org.xwiki.filter.instance.output.DocumentInstanceOutputProperties) XARImportingEvent(com.xpn.xwiki.internal.event.XARImportingEvent) DefaultInputStreamInputSource(org.xwiki.filter.input.DefaultInputStreamInputSource) BeanInputFilterStreamFactory(org.xwiki.filter.input.BeanInputFilterStreamFactory) InputFilterStreamFactory(org.xwiki.filter.input.InputFilterStreamFactory) ObservationManager(org.xwiki.observation.ObservationManager) EntityReferenceSet(org.xwiki.model.reference.EntityReferenceSet) LogQueue(org.xwiki.logging.LogQueue) DocumentInstanceOutputProperties(org.xwiki.filter.instance.output.DocumentInstanceOutputProperties) EntityReference(org.xwiki.model.reference.EntityReference) LoggerManager(org.xwiki.logging.LoggerManager) LocalDocumentReference(org.xwiki.model.reference.LocalDocumentReference) LogEvent(org.xwiki.logging.event.LogEvent) OutputFilterStreamFactory(org.xwiki.filter.output.OutputFilterStreamFactory) BeanOutputFilterStreamFactory(org.xwiki.filter.output.BeanOutputFilterStreamFactory) InputStream(java.io.InputStream) XARImportedEvent(com.xpn.xwiki.internal.event.XARImportedEvent) LoggerListener(org.xwiki.logging.event.LoggerListener) Marker(org.slf4j.Marker) XARInputProperties(org.xwiki.filter.xar.input.XARInputProperties) XarPackage(org.xwiki.xar.XarPackage) Package(com.xpn.xwiki.plugin.packaging.Package)

Example 3 with ObservationManager

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

the class ContextComponentManagerTest method testDeleteWiki.

@Test
public void testDeleteWiki() throws ComponentLookupException, Exception {
    getMockery().checking(new Expectations() {

        {
            allowing(mockWikiDescriptorManager).getCurrentWikiId();
            will(returnValue("wiki"));
            allowing(mockCurrentSpaceReferenceProvider).get();
            will(returnValue(new SpaceReference("space", new WikiReference("wiki"))));
            allowing(mockCurrentDocumentReferenceProvider).get();
            will(returnValue(new DocumentReference("wiki", "space", "document")));
            allowing(mockDocumentAccessBridge).getCurrentUserReference();
            will(returnValue(new DocumentReference("wiki", "XWiki", "user")));
        }
    });
    // Register in the current wiki.
    ComponentManager wikiCM = getComponentManager().getInstance(ComponentManager.class, "wiki");
    DefaultComponentDescriptor<Role> cd = new DefaultComponentDescriptor<Role>();
    cd.setRoleType(Role.class);
    cd.setImplementation(RoleImpl.class);
    wikiCM.registerComponent(cd);
    ComponentManager contextCM = getComponentManager().getInstance(ComponentManager.class, "context");
    Assert.assertNotNull(contextCM.getComponentDescriptor(Role.class, "default"));
    ObservationManager observationManager = getComponentManager().getInstance(ObservationManager.class);
    observationManager.notify(new WikiDeletedEvent("wiki"), null, null);
    Assert.assertNull(contextCM.getComponentDescriptor(Role.class, "default"));
}
Also used : Expectations(org.jmock.Expectations) DefaultComponentDescriptor(org.xwiki.component.descriptor.DefaultComponentDescriptor) SpaceReference(org.xwiki.model.reference.SpaceReference) ComponentManager(org.xwiki.component.manager.ComponentManager) NamespacedComponentManager(org.xwiki.component.manager.NamespacedComponentManager) ObservationManager(org.xwiki.observation.ObservationManager) WikiReference(org.xwiki.model.reference.WikiReference) WikiDeletedEvent(org.xwiki.bridge.event.WikiDeletedEvent) DocumentReference(org.xwiki.model.reference.DocumentReference) Test(org.junit.Test)

Example 4 with ObservationManager

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

the class XarExtensionHandlerTest method setUp.

@Before
public void setUp() throws Exception {
    // mock
    this.contextUser = new DocumentReference(getXWikiContext().getWikiId(), "XWiki", "ExtensionUser");
    this.localXarExtensiontId1 = new ExtensionId("test", "1.0");
    this.localXarExtensiontId2 = new ExtensionId("test", "2.0");
    this.collisionextension1 = new ExtensionId("collisionextension1", "version");
    this.collisionextension2 = new ExtensionId("collisionextension2", "version");
    // classes
    BaseClass styleSheetClass = new BaseClass();
    this.classes.put("StyleSheetExtension", styleSheetClass);
    // checking
    doReturn(true).when(this.oldcore.getSpyXWiki()).hasAttachmentRecycleBin(any(XWikiContext.class));
    getXWikiContext().setUserReference(this.contextUser);
    ((XWikiStubContextProvider) this.componentManager.getInstance(XWikiStubContextProvider.class)).initialize(getXWikiContext());
    CoreConfiguration coreConfiguration = this.componentManager.getInstance(CoreConfiguration.class);
    doReturn(Syntax.PLAIN_1_0).when(coreConfiguration).getDefaultDocumentSyntax();
    // lookup
    this.jobExecutor = this.componentManager.getInstance(JobExecutor.class);
    this.xarExtensionRepository = this.componentManager.getInstance(InstalledExtensionRepository.class, XarExtensionHandler.TYPE);
    this.observation = this.repositoryUtil.getComponentManager().getInstance(ObservationManager.class);
    // Get rid of wiki macro listener
    this.componentManager.<ObservationManager>getInstance(ObservationManager.class).removeListener("RegisterMacrosOnImportListener");
    this.installedExtensionRepository = this.componentManager.getInstance(InstalledExtensionRepository.class, "xar");
    // Programming right is not required for XAR extensions
    doThrow(AccessDeniedException.class).when(this.oldcore.getMockAuthorizationManager()).checkAccess(eq(Right.PROGRAM), any(), any());
}
Also used : XWikiStubContextProvider(com.xpn.xwiki.util.XWikiStubContextProvider) JobExecutor(org.xwiki.job.JobExecutor) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) XWikiContext(com.xpn.xwiki.XWikiContext) ExtensionId(org.xwiki.extension.ExtensionId) ObservationManager(org.xwiki.observation.ObservationManager) CoreConfiguration(com.xpn.xwiki.CoreConfiguration) LocalDocumentReference(org.xwiki.model.reference.LocalDocumentReference) DocumentReference(org.xwiki.model.reference.DocumentReference) XarInstalledExtensionRepository(org.xwiki.extension.xar.internal.repository.XarInstalledExtensionRepository) InstalledExtensionRepository(org.xwiki.extension.repository.InstalledExtensionRepository) Before(org.junit.Before)

Example 5 with ObservationManager

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

the class XWiki method copyWiki.

/**
 * Copy an entire wiki to a target wiki.
 *
 * @param sourceWiki the source wiki identifier
 * @param targetWiki the target wiki identifier
 * @param locale the locale to copy
 * @param clean clean the target wiki before copying
 * @param context see {@link XWikiContext}
 * @return the number of copied documents
 * @throws XWikiException failed to copy wiki
 * @deprecated since 5.3, use {@link WikiManager#copy(String, String, String, boolean, boolean, boolean)} instead
 */
@Deprecated
public int copyWiki(String sourceWiki, String targetWiki, String locale, boolean clean, XWikiContext context) throws XWikiException {
    int documents = copySpaceBetweenWikis(null, sourceWiki, targetWiki, locale, clean, context);
    ObservationManager om = getObservationManager();
    if (om != null) {
        om.notify(new WikiCopiedEvent(sourceWiki, targetWiki), sourceWiki, context);
    }
    return documents;
}
Also used : WikiCopiedEvent(org.xwiki.bridge.event.WikiCopiedEvent) ObservationManager(org.xwiki.observation.ObservationManager)

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