Search in sources :

Example 1 with XWikiStubContextProvider

use of com.xpn.xwiki.util.XWikiStubContextProvider 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 2 with XWikiStubContextProvider

use of com.xpn.xwiki.util.XWikiStubContextProvider in project xwiki-platform by xwiki.

the class ExtensionManagerScriptServiceTest method before.

@Before
public void before() throws Exception {
    // mock
    this.mockXWiki = mock(XWiki.class);
    this.xwikiBridge.getXWikiContext().setWiki(this.mockXWiki);
    this.xwikiBridge.getXWikiContext().setWikiId("xwiki");
    this.contextUser = new DocumentReference(this.xwikiBridge.getXWikiContext().getWikiId(), "XWiki", "ExtensionUser");
    // classes
    BaseClass styleSheetClass = new BaseClass();
    this.classes.put("StyleSheetExtension", styleSheetClass);
    // checking
    this.xwikiBridge.getXWikiContext().setUserReference(this.contextUser);
    ((XWikiStubContextProvider) this.mocker.getInstance(XWikiStubContextProvider.class)).initialize(this.xwikiBridge.getXWikiContext());
    // lookup
    this.scriptService = this.mocker.getInstance(ScriptService.class, "extension");
}
Also used : XWikiStubContextProvider(com.xpn.xwiki.util.XWikiStubContextProvider) ScriptService(org.xwiki.script.service.ScriptService) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) XWiki(com.xpn.xwiki.XWiki) DocumentReference(org.xwiki.model.reference.DocumentReference) Before(org.junit.Before)

Example 3 with XWikiStubContextProvider

use of com.xpn.xwiki.util.XWikiStubContextProvider in project xwiki-platform by xwiki.

the class XWiki method initXWiki.

/**
 * Initialize all xwiki subsystems.
 *
 * @param config the object holding the XWiki configuration read from {@code xwiki.cfg}
 * @param context see {@link XWikiContext}
 * @param engineContext the XWiki object wrapping the {@link javax.servlet.ServletContext} and which allows to set
 *            data that live on as long as the XWiki webapp is not stopped in the Servlet Container
 * @param noupdate true if the whole initialization should be done (create mandatory xlcasses, initialize stats
 *            service), i.e. if this is not an update, and false otherwise
 * @throws XWikiException if an error happened during initialization (failure to initialize some cache for example)
 * @deprecated since 6.1M2, use {@link #initXWiki(XWikiContext, XWikiEngineContext, boolean)} instead
 */
@Deprecated
public void initXWiki(XWikiConfig config, XWikiContext context, XWikiEngineContext engineContext, boolean noupdate) throws XWikiException {
    getProgress().pushLevelProgress(4, this);
    try {
        getProgress().startStep(this);
        setDatabase(context.getMainXWiki());
        setEngineContext(engineContext);
        context.setWiki(this);
        // "Pre-initialize" XWikiStubContextProvider with a XWikiContext containing a XWiki instance as soon as
        // possible
        Utils.<XWikiStubContextProvider>getComponent(XWikiStubContextProvider.class).initialize(context);
        // Prepare the store
        if (config != null) {
            setConfig(config);
        }
        try {
            initializeStores();
        } catch (ComponentLookupException e) {
            throw new XWikiException(XWikiException.MODULE_XWIKI_STORE, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to initialize stores", e);
        }
        setCriteriaService((XWikiCriteriaService) createClassFromConfig("xwiki.criteria.class", "com.xpn.xwiki.criteria.impl.XWikiCriteriaServiceImpl", context));
        // "Pre-initialize" XWikiStubContextProvider so that rendering engine, plugins or listeners reacting to
        // potential document changes can use it
        Utils.<XWikiStubContextProvider>getComponent(XWikiStubContextProvider.class).initialize(context);
        getProgress().endStep(this);
        getProgress().startStep(this);
        // Make sure these classes exists
        if (noupdate) {
            initializeMandatoryDocuments(context);
            getStatsService(context);
        }
        getProgress().endStep(this);
        getProgress().startStep(this);
        // Prepare the Plugin Engine
        preparePlugins(context);
        getProgress().endStep(this);
        getProgress().startStep(this);
        String ro = getConfiguration().getProperty("xwiki.readonly", "no");
        this.isReadOnly = ("yes".equalsIgnoreCase(ro) || "true".equalsIgnoreCase(ro) || "1".equalsIgnoreCase(ro));
        // Save the configured syntaxes
        String syntaxes = getConfiguration().getProperty("xwiki.rendering.syntaxes", "xwiki/1.0");
        this.configuredSyntaxes = Arrays.asList(StringUtils.split(syntaxes, " ,"));
        getObservationManager().addListener(this);
    } finally {
        getProgress().popLevelProgress(this);
    }
}
Also used : XWikiStubContextProvider(com.xpn.xwiki.util.XWikiStubContextProvider) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) ParseGroovyFromString(com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString) IncludeServletAsString(com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString)

Example 4 with XWikiStubContextProvider

use of com.xpn.xwiki.util.XWikiStubContextProvider in project xwiki-platform by xwiki.

the class AbstractBridgedXWikiComponentTestCase method setUp.

@Override
protected void setUp() throws Exception {
    super.setUp();
    // Statically store the component manager in {@link Utils} to be able to access it without
    // the context.
    Utils.setComponentManager(getComponentManager());
    this.context = new XWikiContext();
    this.context.setWikiId("xwiki");
    this.context.setMainXWiki("xwiki");
    // Make sure response.encodeURL() calls don't fail
    Mock xwikiResponse = mock(XWikiResponse.class);
    xwikiResponse.stubs().method("setLocale");
    xwikiResponse.stubs().method("encodeURL").will(new CustomStub("Implements XWikiResponse.encodeURL") {

        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            return invocation.parameterValues.get(0);
        }
    });
    this.context.setResponse((XWikiResponse) xwikiResponse.proxy());
    // We need to initialize the Component Manager so that the components can be looked up
    getContext().put(ComponentManager.class.getName(), getComponentManager());
    // Bridge with old XWiki Context, required for old code.
    Execution execution = getComponentManager().getInstance(Execution.class);
    this.context.declareInExecutionContext(execution.getContext());
    XWikiStubContextProvider stubContextProvider = getComponentManager().getInstance(XWikiStubContextProvider.class);
    stubContextProvider.initialize(this.context);
    // Bridge with XWiki Context Provider, required by newer code.
    Mock mockContextProvider = mock(Provider.class);
    mockContextProvider.stubs().method("get").will(returnValue(this.context));
    DefaultComponentDescriptor<Provider<XWikiContext>> contextProviderDescriptor = new DefaultComponentDescriptor<Provider<XWikiContext>>();
    contextProviderDescriptor.setRoleType(new DefaultParameterizedType(null, Provider.class, XWikiContext.class));
    contextProviderDescriptor.setRoleHint("default");
    getComponentManager().registerComponent(contextProviderDescriptor, (Provider<XWikiContext>) mockContextProvider.proxy());
    // Since the oldcore module draws the Servlet Environment in its dependencies we need to ensure it's set up
    // correctly with a Servlet Context.
    ServletEnvironment environment = getComponentManager().getInstance(Environment.class);
    Mock mockServletContext = mock(ServletContext.class);
    environment.setServletContext((ServletContext) mockServletContext.proxy());
    mockServletContext.stubs().method("getResourceAsStream").will(returnValue(null));
    mockServletContext.stubs().method("getResource").will(returnValue(null));
    mockServletContext.stubs().method("getAttribute").with(eq("javax.servlet.context.tempdir")).will(returnValue(new File(System.getProperty("java.io.tmpdir"))));
    File testDirectory = new File("target/test-" + new Date().getTime());
    this.temporaryDirectory = new File(testDirectory, "temporary-dir");
    this.permanentDirectory = new File(testDirectory, "permanent-dir");
    environment.setTemporaryDirectory(this.temporaryDirectory);
    environment.setPermanentDirectory(this.permanentDirectory);
    Mock mockCoreConfiguration = registerMockComponent(CoreConfiguration.class);
    mockCoreConfiguration.stubs().method("getDefaultDocumentSyntax").will(returnValue(Syntax.XWIKI_1_0));
    this.mockWikiDescriptorManager = registerMockComponent(WikiDescriptorManager.class);
    this.mockWikiDescriptorManager.stubs().method("getCurrentWikiId").will(new CustomStub("Implements WikiDescriptorManager.getCurrentWikiId") {

        @Override
        public String invoke(Invocation invocation) throws Throwable {
            return getContext().getWikiId();
        }
    });
    this.mockWikiDescriptorManager.stubs().method("getMainWikiId").will(new CustomStub("Implements WikiDescriptorManager.getMainWikiId") {

        @Override
        public String invoke(Invocation invocation) throws Throwable {
            return getContext().getMainXWiki();
        }
    });
    // In order not to create a cyclic dependency we have the platform-rendering-xwiki module (which contains
    // XWikiWikiModel requires for oldcore testing) not depend on platform-rendering-configuration-default. As a
    // consequence we need to provide a mock ExtendedRenderingConfiguration component as otherwise injecting
    // WikiModel would fail (since XWikiWikiModel depends on ExtendedRenderingConfiguration).
    registerMockComponent(ExtendedRenderingConfiguration.class);
}
Also used : XWikiStubContextProvider(com.xpn.xwiki.util.XWikiStubContextProvider) Invocation(org.jmock.core.Invocation) WikiDescriptorManager(org.xwiki.wiki.descriptor.WikiDescriptorManager) XWikiContext(com.xpn.xwiki.XWikiContext) Mock(org.jmock.Mock) Date(java.util.Date) Provider(javax.inject.Provider) XWikiStubContextProvider(com.xpn.xwiki.util.XWikiStubContextProvider) Execution(org.xwiki.context.Execution) DefaultComponentDescriptor(org.xwiki.component.descriptor.DefaultComponentDescriptor) CustomStub(org.jmock.core.stub.CustomStub) ComponentManager(org.xwiki.component.manager.ComponentManager) ServletEnvironment(org.xwiki.environment.internal.ServletEnvironment) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType) File(java.io.File)

Example 5 with XWikiStubContextProvider

use of com.xpn.xwiki.util.XWikiStubContextProvider in project xwiki-platform by xwiki.

the class MockitoOldcore method before.

public void before(Class<?> testClass) throws Exception {
    // Statically store the component manager in {@link Utils} to be able to access it without
    // the context.
    Utils.setComponentManager(getMocker());
    this.context = new XWikiContext();
    getXWikiContext().setWikiId("xwiki");
    getXWikiContext().setMainXWiki("xwiki");
    this.spyXWiki = spy(new XWiki());
    getXWikiContext().setWiki(this.spyXWiki);
    this.mockHibernateStore = mock(XWikiHibernateStore.class);
    this.mockVersioningStore = mock(XWikiVersioningStoreInterface.class);
    this.mockRightService = mock(XWikiRightService.class);
    this.mockGroupService = mock(XWikiGroupService.class);
    doReturn(this.mockHibernateStore).when(this.spyXWiki).getStore();
    doReturn(this.mockHibernateStore).when(this.spyXWiki).getHibernateStore();
    doReturn(this.mockVersioningStore).when(this.spyXWiki).getVersioningStore();
    doReturn(this.mockRightService).when(this.spyXWiki).getRightService();
    doReturn(this.mockGroupService).when(this.spyXWiki).getGroupService(getXWikiContext());
    // We need to initialize the Component Manager so that the components can be looked up
    getXWikiContext().put(ComponentManager.class.getName(), getMocker());
    if (testClass.getAnnotation(AllComponents.class) != null) {
        // If @AllComponents is enabled force mocking AuthorizationManager and ContextualAuthorizationManager if not
        // already mocked
        this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class, false);
        this.mockContextualAuthorizationManager = getMocker().registerMockComponent(ContextualAuthorizationManager.class, false);
    } else {
        // Make sure an AuthorizationManager and a ContextualAuthorizationManager is available
        if (!getMocker().hasComponent(AuthorizationManager.class)) {
            this.mockAuthorizationManager = getMocker().registerMockComponent(AuthorizationManager.class);
        }
        if (!getMocker().hasComponent(ContextualAuthorizationManager.class)) {
            this.mockContextualAuthorizationManager = getMocker().registerMockComponent(ContextualAuthorizationManager.class);
        }
    }
    // Make sure a default ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class)) {
        this.configurationSource = getMocker().registerMemoryConfigurationSource();
    }
    // Make sure a "xwikicfg" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, XWikiCfgConfigurationSource.ROLEHINT)) {
        this.xwikicfgConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor(XWikiCfgConfigurationSource.ROLEHINT), this.xwikicfgConfigurationSource);
    }
    // Make sure a "wiki" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "wiki")) {
        this.wikiConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("wiki"), this.wikiConfigurationSource);
    }
    // Make sure a "space" ConfigurationSource is available
    if (!getMocker().hasComponent(ConfigurationSource.class, "space")) {
        this.spaceConfigurationSource = new MockConfigurationSource();
        getMocker().registerComponent(MockConfigurationSource.getDescriptor("space"), this.spaceConfigurationSource);
    }
    // correctly with a Servlet Context.
    if (getMocker().hasComponent(Environment.class) && getMocker().getInstance(Environment.class) instanceof ServletEnvironment) {
        ServletEnvironment environment = getMocker().getInstance(Environment.class);
        ServletContext servletContextMock = mock(ServletContext.class);
        environment.setServletContext(servletContextMock);
        when(servletContextMock.getAttribute("javax.servlet.context.tempdir")).thenReturn(new File(System.getProperty("java.io.tmpdir")));
        File testDirectory = new File("target/test-" + new Date().getTime());
        this.temporaryDirectory = new File(testDirectory, "temporary-dir");
        this.permanentDirectory = new File(testDirectory, "permanent-dir");
        environment.setTemporaryDirectory(this.temporaryDirectory);
        environment.setPermanentDirectory(this.permanentDirectory);
    }
    // Initialize the Execution Context
    if (this.componentManager.hasComponent(ExecutionContextManager.class)) {
        ExecutionContextManager ecm = this.componentManager.getInstance(ExecutionContextManager.class);
        ExecutionContext ec = new ExecutionContext();
        ecm.initialize(ec);
    }
    // Bridge with old XWiki Context, required for old code.
    Execution execution;
    if (this.componentManager.hasComponent(Execution.class)) {
        execution = this.componentManager.getInstance(Execution.class);
    } else {
        execution = this.componentManager.registerMockComponent(Execution.class);
    }
    ExecutionContext econtext;
    if (MockUtil.isMock(execution)) {
        econtext = new ExecutionContext();
        when(execution.getContext()).thenReturn(econtext);
    } else {
        econtext = execution.getContext();
    }
    // Set a few standard things in the ExecutionContext
    econtext.setProperty(XWikiContext.EXECUTIONCONTEXT_KEY, this.context);
    this.scriptContext = (ScriptContext) econtext.getProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID);
    if (this.scriptContext == null) {
        this.scriptContext = new SimpleScriptContext();
        econtext.setProperty(ScriptExecutionContextInitializer.SCRIPT_CONTEXT_ID, this.scriptContext);
    }
    if (!this.componentManager.hasComponent(ScriptContextManager.class)) {
        ScriptContextManager scriptContextManager = this.componentManager.registerMockComponent(ScriptContextManager.class);
        when(scriptContextManager.getCurrentScriptContext()).thenReturn(this.scriptContext);
        when(scriptContextManager.getScriptContext()).thenReturn(this.scriptContext);
    }
    // Initialize XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER)) {
        Provider<XWikiContext> xcontextProvider = this.componentManager.registerMockComponent(XWikiContext.TYPE_PROVIDER);
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }
    // Initialize readonly XWikiContext provider
    if (!this.componentManager.hasComponent(XWikiContext.TYPE_PROVIDER, "readonly")) {
        Provider<XWikiContext> xcontextProvider = this.componentManager.registerMockComponent(XWikiContext.TYPE_PROVIDER, "readonly");
        when(xcontextProvider.get()).thenReturn(this.context);
    } else {
        Provider<XWikiContext> xcontextProvider = this.componentManager.getInstance(XWikiContext.TYPE_PROVIDER);
        if (MockUtil.isMock(xcontextProvider)) {
            when(xcontextProvider.get()).thenReturn(this.context);
        }
    }
    // Initialize stub context provider
    if (this.componentManager.hasComponent(XWikiStubContextProvider.class)) {
        XWikiStubContextProvider stubContextProvider = this.componentManager.getInstance(XWikiStubContextProvider.class);
        if (!MockUtil.isMock(stubContextProvider)) {
            stubContextProvider.initialize(this.context);
        }
    }
    // Make sure to have a mocked CoreConfiguration (even if one already exist)
    if (!this.componentManager.hasComponent(CoreConfiguration.class)) {
        CoreConfiguration coreConfigurationMock = this.componentManager.registerMockComponent(CoreConfiguration.class);
        when(coreConfigurationMock.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
    } else {
        CoreConfiguration coreConfiguration = this.componentManager.registerMockComponent(CoreConfiguration.class, false);
        if (MockUtil.isMock(coreConfiguration)) {
            when(coreConfiguration.getDefaultDocumentSyntax()).thenReturn(Syntax.XWIKI_2_1);
        }
    }
    // Set a context ComponentManager if none exist
    if (!this.componentManager.hasComponent(ComponentManager.class, "context")) {
        DefaultComponentDescriptor<ComponentManager> componentManagerDescriptor = new DefaultComponentDescriptor<>();
        componentManagerDescriptor.setRoleHint("context");
        componentManagerDescriptor.setRoleType(ComponentManager.class);
        this.componentManager.registerComponent(componentManagerDescriptor, this.componentManager);
    }
    // XWiki
    doAnswer(new Answer<XWikiDocument>() {

        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument doc = invocation.getArgument(0);
            String revision = invocation.getArgument(1);
            if (StringUtils.equals(revision, doc.getVersion())) {
                return doc;
            }
            // TODO: implement version store mocking
            return new XWikiDocument(doc.getDocumentReference());
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {

        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = invocation.getArgument(0);
            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }
            XWikiDocument document = documents.get(target);
            if (document == null) {
                document = new XWikiDocument(target, target.getLocale());
                document.setSyntax(Syntax.PLAIN_1_0);
                document.setOriginalDocument(document.clone());
            }
            return document;
        }
    }).when(getSpyXWiki()).getDocument(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<XWikiDocument>() {

        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument target = invocation.getArgument(0);
            return getSpyXWiki().getDocument(target.getDocumentReferenceWithLocale(), invocation.getArgument(1));
        }
    }).when(getSpyXWiki()).getDocument(anyXWikiDocument(), any(XWikiContext.class));
    doAnswer(new Answer<Boolean>() {

        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            DocumentReference target = (DocumentReference) invocation.getArguments()[0];
            if (target.getLocale() == null) {
                target = new DocumentReference(target, Locale.ROOT);
            }
            return documents.containsKey(target);
        }
    }).when(getSpyXWiki()).exists(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);
            String comment = invocation.getArgument(1);
            boolean minorEdit = invocation.getArgument(2);
            boolean isNew = document.isNew();
            document.setComment(StringUtils.defaultString(comment));
            document.setMinorEdit(minorEdit);
            if (document.isContentDirty() || document.isMetaDataDirty()) {
                document.setDate(new Date());
                if (document.isContentDirty()) {
                    document.setContentUpdateDate(new Date());
                    document.setContentAuthorReference(document.getAuthorReference());
                }
                document.incrementVersion();
                document.setContentDirty(false);
                document.setMetaDataDirty(false);
            }
            document.setNew(false);
            document.setStore(getMockStore());
            XWikiDocument previousDocument = documents.get(document.getDocumentReferenceWithLocale());
            if (previousDocument != null && previousDocument != document) {
                for (XWikiAttachment attachment : document.getAttachmentList()) {
                    if (!attachment.isContentDirty()) {
                        attachment.setAttachment_content(previousDocument.getAttachment(attachment.getFilename()).getAttachment_content());
                    }
                }
            }
            XWikiDocument originalDocument = document.getOriginalDocument();
            if (originalDocument == null) {
                originalDocument = spyXWiki.getDocument(document.getDocumentReferenceWithLocale(), context);
                document.setOriginalDocument(originalDocument);
            }
            XWikiDocument savedDocument = document.clone();
            documents.put(document.getDocumentReferenceWithLocale(), savedDocument);
            if (isNew) {
                if (notifyDocumentCreatedEvent) {
                    getObservationManager().notify(new DocumentCreatedEvent(document.getDocumentReference()), document, getXWikiContext());
                }
            } else {
                if (notifyDocumentUpdatedEvent) {
                    getObservationManager().notify(new DocumentUpdatedEvent(document.getDocumentReference()), document, getXWikiContext());
                }
            }
            // Set the document as it's original document
            savedDocument.setOriginalDocument(savedDocument.clone());
            return null;
        }
    }).when(getSpyXWiki()).saveDocument(anyXWikiDocument(), any(String.class), anyBoolean(), anyXWikiContext());
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);
            documents.remove(document.getDocumentReferenceWithLocale());
            if (notifyDocumentDeletedEvent) {
                getObservationManager().notify(new DocumentDeletedEvent(document.getDocumentReference()), document, getXWikiContext());
            }
            return null;
        }
    }).when(getSpyXWiki()).deleteDocument(anyXWikiDocument(), any(Boolean.class), anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {

        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            return getSpyXWiki().getDocument((DocumentReference) invocation.getArguments()[0], invocation.getArgument(1)).getXClass();
        }
    }).when(getSpyXWiki()).getXClass(any(DocumentReference.class), anyXWikiContext());
    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            return getXWikiContext().getLanguage();
        }
    }).when(getSpyXWiki()).getLanguagePreference(anyXWikiContext());
    getXWikiContext().setLocale(Locale.ENGLISH);
    // XWikiStoreInterface
    when(getMockStore().getTranslationList(anyXWikiDocument(), anyXWikiContext())).then(new Answer<List<String>>() {

        @Override
        public List<String> answer(InvocationOnMock invocation) throws Throwable {
            XWikiDocument document = invocation.getArgument(0);
            List<String> translations = new ArrayList<String>();
            for (XWikiDocument storedDocument : documents.values()) {
                Locale storedLocale = storedDocument.getLocale();
                if (!storedLocale.equals(Locale.ROOT) && storedDocument.getDocumentReference().equals(document.getDocumentReference())) {
                    translations.add(storedLocale.toString());
                }
            }
            return translations;
        }
    });
    when(getMockStore().loadXWikiDoc(anyXWikiDocument(), anyXWikiContext())).then(new Answer<XWikiDocument>() {

        @Override
        public XWikiDocument answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReference();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }
            return getSpyXWiki().getDocument(reference, xcontext);
        }
    });
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // The store is based on the contex for the wiki
            DocumentReference reference = invocation.<XWikiDocument>getArgument(0).getDocumentReferenceWithLocale();
            XWikiContext xcontext = invocation.getArgument(1);
            if (!xcontext.getWikiReference().equals(reference.getWikiReference())) {
                reference = reference.setWikiReference(xcontext.getWikiReference());
            }
            documents.remove(reference);
            return null;
        }
    }).when(getMockStore()).deleteXWikiDoc(anyXWikiDocument(), anyXWikiContext());
    // Users
    doAnswer(new Answer<BaseClass>() {

        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);
            XWikiDocument userDocument = getSpyXWiki().getDocument(new DocumentReference(USER_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);
            final BaseClass userClass = userDocument.getXClass();
            if (userDocument.isNew()) {
                userClass.addTextField("first_name", "First Name", 30);
                userClass.addTextField("last_name", "Last Name", 30);
                userClass.addEmailField("email", "e-Mail", 30);
                userClass.addPasswordField("password", "Password", 10);
                userClass.addBooleanField("active", "Active", "active");
                userClass.addTextAreaField("comment", "Comment", 40, 5);
                userClass.addTextField("avatar", "Avatar", 30);
                userClass.addTextField("phone", "Phone", 30);
                userClass.addTextAreaField("address", "Address", 40, 3);
                getSpyXWiki().saveDocument(userDocument, xcontext);
            }
            return userClass;
        }
    }).when(getSpyXWiki()).getUserClass(anyXWikiContext());
    doAnswer(new Answer<BaseClass>() {

        @Override
        public BaseClass answer(InvocationOnMock invocation) throws Throwable {
            XWikiContext xcontext = invocation.getArgument(0);
            XWikiDocument groupDocument = getSpyXWiki().getDocument(new DocumentReference(GROUP_CLASS, new WikiReference(xcontext.getWikiId())), xcontext);
            final BaseClass groupClass = groupDocument.getXClass();
            if (groupDocument.isNew()) {
                groupClass.addTextField("member", "Member", 30);
                getSpyXWiki().saveDocument(groupDocument, xcontext);
            }
            return groupClass;
        }
    }).when(getSpyXWiki()).getGroupClass(anyXWikiContext());
    // This allows, for example, using @ComponentList to use the real Query Manager, in integration tests.
    if (!this.componentManager.hasComponent(QueryManager.class)) {
        mockQueryManager();
    }
    when(getMockStore().getQueryManager()).then(new Answer<QueryManager>() {

        @Override
        public QueryManager answer(InvocationOnMock invocation) throws Throwable {
            return getQueryManager();
        }
    });
    // This allows, for example, using @ComponentList to use the real WikiDescriptorManager, in integration tests.
    if (!this.componentManager.hasComponent(WikiDescriptorManager.class)) {
        this.wikiDescriptorManager = getMocker().registerMockComponent(WikiDescriptorManager.class);
        when(this.wikiDescriptorManager.getMainWikiId()).then(new Answer<String>() {

            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getMainXWiki();
            }
        });
        when(this.wikiDescriptorManager.getCurrentWikiId()).then(new Answer<String>() {

            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return getXWikiContext().getWikiId();
            }
        });
    }
}
Also used : XWikiStubContextProvider(com.xpn.xwiki.util.XWikiStubContextProvider) Locale(java.util.Locale) ExecutionContextManager(org.xwiki.context.ExecutionContextManager) DocumentUpdatedEvent(org.xwiki.bridge.event.DocumentUpdatedEvent) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) XWikiVersioningStoreInterface(com.xpn.xwiki.store.XWikiVersioningStoreInterface) Execution(org.xwiki.context.Execution) DefaultComponentDescriptor(org.xwiki.component.descriptor.DefaultComponentDescriptor) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) List(java.util.List) ArrayList(java.util.ArrayList) ArgumentMatchers.anyBoolean(org.mockito.ArgumentMatchers.anyBoolean) LocalDocumentReference(org.xwiki.model.reference.LocalDocumentReference) DocumentReference(org.xwiki.model.reference.DocumentReference) MemoryConfigurationSource(org.xwiki.configuration.internal.MemoryConfigurationSource) XWikiCfgConfigurationSource(com.xpn.xwiki.internal.XWikiCfgConfigurationSource) MockConfigurationSource(org.xwiki.test.internal.MockConfigurationSource) ConfigurationSource(org.xwiki.configuration.ConfigurationSource) WikiDescriptorManager(org.xwiki.wiki.descriptor.WikiDescriptorManager) OldcoreMatchers.anyXWikiContext(com.xpn.xwiki.test.mockito.OldcoreMatchers.anyXWikiContext) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) AllComponents(org.xwiki.test.annotation.AllComponents) ExecutionContext(org.xwiki.context.ExecutionContext) XWikiRightService(com.xpn.xwiki.user.api.XWikiRightService) ServletEnvironment(org.xwiki.environment.internal.ServletEnvironment) Environment(org.xwiki.environment.Environment) WikiReference(org.xwiki.model.reference.WikiReference) File(java.io.File) ContextualAuthorizationManager(org.xwiki.security.authorization.ContextualAuthorizationManager) MockConfigurationSource(org.xwiki.test.internal.MockConfigurationSource) CoreConfiguration(com.xpn.xwiki.CoreConfiguration) OldcoreMatchers.anyXWikiDocument(com.xpn.xwiki.test.mockito.OldcoreMatchers.anyXWikiDocument) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ComponentManager(org.xwiki.component.manager.ComponentManager) MockitoComponentManager(org.xwiki.test.mockito.MockitoComponentManager) ServletContext(javax.servlet.ServletContext) ServletEnvironment(org.xwiki.environment.internal.ServletEnvironment) XWikiGroupService(com.xpn.xwiki.user.api.XWikiGroupService) SimpleScriptContext(javax.script.SimpleScriptContext) DocumentCreatedEvent(org.xwiki.bridge.event.DocumentCreatedEvent) ScriptContextManager(org.xwiki.script.ScriptContextManager) Date(java.util.Date) DocumentDeletedEvent(org.xwiki.bridge.event.DocumentDeletedEvent) XWikiHibernateStore(com.xpn.xwiki.store.XWikiHibernateStore) InvocationOnMock(org.mockito.invocation.InvocationOnMock) QueryManager(org.xwiki.query.QueryManager) AuthorizationManager(org.xwiki.security.authorization.AuthorizationManager) ContextualAuthorizationManager(org.xwiki.security.authorization.ContextualAuthorizationManager)

Aggregations

XWikiStubContextProvider (com.xpn.xwiki.util.XWikiStubContextProvider)8 XWikiContext (com.xpn.xwiki.XWikiContext)5 CoreConfiguration (com.xpn.xwiki.CoreConfiguration)3 XWiki (com.xpn.xwiki.XWiki)3 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)3 File (java.io.File)3 Before (org.junit.Before)3 ComponentManager (org.xwiki.component.manager.ComponentManager)3 Execution (org.xwiki.context.Execution)3 ServletEnvironment (org.xwiki.environment.internal.ServletEnvironment)3 DocumentReference (org.xwiki.model.reference.DocumentReference)3 ParseGroovyFromString (com.xpn.xwiki.internal.render.groovy.ParseGroovyFromString)2 IncludeServletAsString (com.xpn.xwiki.web.includeservletasstring.IncludeServletAsString)2 Date (java.util.Date)2 ServletContext (javax.servlet.ServletContext)2 DefaultComponentDescriptor (org.xwiki.component.descriptor.DefaultComponentDescriptor)2 LocalDocumentReference (org.xwiki.model.reference.LocalDocumentReference)2 WikiDescriptorManager (org.xwiki.wiki.descriptor.WikiDescriptorManager)2 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)1 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)1