Search in sources :

Example 6 with XWikiServletRequestStub

use of com.xpn.xwiki.web.XWikiServletRequestStub in project xwiki-platform by xwiki.

the class SyndEntryDocumentSourceTest method mockUp.

private void mockUp() throws Exception {
    final Map<String, XWikiDocument> docs = new HashMap<String, XWikiDocument>();
    final XWikiContext context = getContext();
    // Set URL/Request
    context.setRequest(new XWikiServletRequestStub());
    context.setURL(new URL("http://localhost:8080/xwiki/bin/view/MilkyWay/Fidis"));
    final XWiki xwiki = new XWiki(new XWikiConfig(), context) {

        @Override
        public String getXWikiPreference(String prefname, String defaultValue, XWikiContext context) {
            return defaultValue;
        }
    };
    context.setURLFactory(new XWikiServletURLFactory(new URL("http://www.xwiki.org/"), "xwiki/", "bin/"));
    final Mock mockXWikiStore = mock(XWikiHibernateStore.class, new Class[] { XWiki.class, XWikiContext.class }, new Object[] { xwiki, context });
    mockXWikiStore.stubs().method("loadXWikiDoc").will(new CustomStub("Implements XWikiStoreInterface.loadXWikiDoc") {

        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            XWikiDocument shallowDoc = (XWikiDocument) invocation.parameterValues.get(0);
            if (docs.containsKey(shallowDoc.getName())) {
                return docs.get(shallowDoc.getName());
            } else {
                return shallowDoc;
            }
        }
    });
    mockXWikiStore.stubs().method("saveXWikiDoc").will(new CustomStub("Implements XWikiStoreInterface.saveXWikiDoc") {

        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            XWikiDocument document = (XWikiDocument) invocation.parameterValues.get(0);
            document.setNew(false);
            document.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
            docs.put(document.getName(), document);
            return null;
        }
    });
    mockXWikiStore.stubs().method("getTranslationList").will(returnValue(Collections.EMPTY_LIST));
    mockXWikiStore.stubs().method("exists").will(returnValue(false));
    final Mock mockXWikiVersioningStore = mock(XWikiHibernateVersioningStore.class, new Class[] { XWiki.class, XWikiContext.class }, new Object[] { xwiki, context });
    mockXWikiVersioningStore.stubs().method("getXWikiDocumentArchive").will(returnValue(null));
    mockXWikiVersioningStore.stubs().method("resetRCSArchive").will(returnValue(null));
    xwiki.setStore((XWikiStoreInterface) mockXWikiStore.proxy());
    xwiki.setVersioningStore((XWikiVersioningStoreInterface) mockXWikiVersioningStore.proxy());
    final Mock mockXWikiRightsService = mock(XWikiRightServiceImpl.class, new Class[] {}, new Object[] {});
    mockXWikiRightsService.stubs().method("hasAccessLevel").will(new CustomStub("Implements XWikiRightService.hasAccessLevel") {

        @Override
        public Object invoke(Invocation invocation) throws Throwable {
            // String right = (String) invocation.parameterValues.get(0);
            String user = (String) invocation.parameterValues.get(1);
            // we give access to all the users with an even name length
            return new Boolean(user.length() % 2 == 0);
        }
    });
    xwiki.setRightService((XWikiRightService) mockXWikiRightsService.proxy());
}
Also used : XWikiServletRequestStub(com.xpn.xwiki.web.XWikiServletRequestStub) XWikiServletURLFactory(com.xpn.xwiki.web.XWikiServletURLFactory) Invocation(org.jmock.core.Invocation) HashMap(java.util.HashMap) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) URL(java.net.URL) Mock(org.jmock.Mock) XWikiStoreInterface(com.xpn.xwiki.store.XWikiStoreInterface) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) CustomStub(org.jmock.core.stub.CustomStub) XWikiConfig(com.xpn.xwiki.XWikiConfig)

Example 7 with XWikiServletRequestStub

use of com.xpn.xwiki.web.XWikiServletRequestStub in project xwiki-platform by xwiki.

the class JobRequestContextInitializer method onEvent.

@Override
public void onEvent(Event event, Object source, Object data) {
    JobStartedEvent jobStartedEvent = (JobStartedEvent) event;
    JobRequestContext jobRequestContext = jobStartedEvent.getRequest().getProperty(JobRequestContext.KEY);
    if (jobRequestContext != null) {
        XWikiContext xcontext = this.xcontextProvider.get();
        if (xcontext != null) {
            // Wiki id
            if (jobRequestContext.isWikiIdSet()) {
                xcontext.setWikiId(jobRequestContext.getWikiId());
            }
            // User
            if (jobRequestContext.isUserReferenceSet()) {
                xcontext.setUserReference(jobRequestContext.getUserReference());
            }
            // Document
            if (jobRequestContext.isDocumentSet()) {
                XWikiDocument document = getDocument(jobRequestContext, xcontext);
                xcontext.setDoc(document);
            }
            // Secure document
            if (jobRequestContext.isSDocumentSet()) {
                XWikiDocument sdocument = getSDocument(jobRequestContext, xcontext);
                xcontext.put(XWikiDocument.CKEY_SDOC, sdocument);
            }
            // Request
            if (jobRequestContext.isRequestSet()) {
                xcontext.setRequest(new XWikiServletRequestStub(jobRequestContext.getRequestURL(), jobRequestContext.getRequestParameters()));
            }
        }
    }
}
Also used : XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiServletRequestStub(com.xpn.xwiki.web.XWikiServletRequestStub) XWikiContext(com.xpn.xwiki.XWikiContext) JobStartedEvent(org.xwiki.job.event.JobStartedEvent) JobRequestContext(com.xpn.xwiki.job.JobRequestContext)

Example 8 with XWikiServletRequestStub

use of com.xpn.xwiki.web.XWikiServletRequestStub in project xwiki-platform by xwiki.

the class OldCoreHelper method createXWikiContext.

/**
 * @param wikiId id of the wiki for which to prepare the XWiki Context (e.g. {@code xwiki})
 * @param hibernateConfig the Hibernate config fill containing the database definition (JDBC driver, username and
 *            password, etc)
 * @return a valid XWikiContext using the passed Hibernate configuration and passed database name
 * @throws Exception failed to initialize context.
 */
// TODO: Replace the Hibernate config file with a list of parameters required for the packaging operation
private XWikiContext createXWikiContext() throws Exception {
    Utils.setComponentManager(this.componentManager);
    this.xcontext = new XWikiContext();
    this.xcontext.put(ComponentManager.class.getName(), this.componentManager);
    // Initialize the Container fields (request, response, session).
    try {
        ExecutionContext econtext = new ExecutionContext();
        // Bridge with old XWiki Context, required for old code.
        this.xcontext.declareInExecutionContext(econtext);
        this.ecim.initialize(econtext);
    } catch (ExecutionContextException e) {
        throw new Exception("Failed to initialize Execution Context.", e);
    }
    this.xcontext.setWikiId(wikiId);
    this.xcontext.setMainXWiki(wikiId);
    // Use a dummy Request/Response even in daemon mode so that XWiki's initialization can create a Servlet URL
    // Factory and any code requiring those objects will work.
    this.xcontext.setRequest(new XWikiServletRequestStub());
    this.xcontext.setResponse(new XWikiServletResponseStub());
    // Use a dummy URL so that XWiki's initialization can create a Servlet URL Factory. We could also have
    // registered a custom XWikiURLFactory against XWikiURLFactoryService but it's more work.
    this.xcontext.setURL(new URL("http://localhost/xwiki/bin/DummyAction/DumySpace/DummyPage"));
    // Set a dummy Document in the context to act as the current document since when a document containing
    // objects is imported it'll generate Object diff events and the algorithm to compute an object diff
    // currently requires rendering object properties, which requires a current document in the context.
    this.xcontext.setDoc(new XWikiDocument(new DocumentReference(wikiId, "dummySpace", "dummyPage")));
    XWikiConfig config = new XWikiConfig();
    config.put("xwiki.store.class", "com.xpn.xwiki.store.XWikiHibernateStore");
    // The XWikiConfig object requires path to be in unix format (i.e. with forward slashes)
    String hibernateConfigInUnixFormat = hibernateConfig.getPath().replace('\\', '/');
    config.put("xwiki.store.hibernate.path", hibernateConfigInUnixFormat);
    config.put("xwiki.store.hibernate.updateschema", "1");
    // Enable backlinks so that when documents are imported their backlinks will be saved too
    config.put("xwiki.backlinks", "1");
    XWiki xwiki = new XWiki(config, this.xcontext, null, true);
    this.xcontext.setUserReference(new DocumentReference("xwiki", "XWiki", "superadmin"));
    try {
        this.xcontext.setURLFactory(new XWikiServletURLFactory(new URL("http://localhost:8080"), "xwiki/", "bin/"));
    } catch (MalformedURLException e) {
        // doesn't work with external code.
        throw new XWikiException(XWikiException.MODULE_XWIKI_PLUGINS, XWikiException.ERROR_XWIKI_UNKNOWN, "Failed to set up URL Factory", e);
    }
    // Trigger extensions that need to initialize the database (create classes, etc.)
    xwiki.initializeWiki(this.xcontext.getMainXWiki(), true, this.xcontext);
    return this.xcontext;
}
Also used : XWikiServletRequestStub(com.xpn.xwiki.web.XWikiServletRequestStub) XWikiServletURLFactory(com.xpn.xwiki.web.XWikiServletURLFactory) MalformedURLException(java.net.MalformedURLException) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) ExecutionContextException(org.xwiki.context.ExecutionContextException) XWikiException(com.xpn.xwiki.XWikiException) ComponentLookupException(org.xwiki.component.manager.ComponentLookupException) MalformedURLException(java.net.MalformedURLException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ExecutionContextException(org.xwiki.context.ExecutionContextException) URL(java.net.URL) XWikiServletResponseStub(com.xpn.xwiki.web.XWikiServletResponseStub) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ExecutionContext(org.xwiki.context.ExecutionContext) EmbeddableComponentManager(org.xwiki.component.embed.EmbeddableComponentManager) ComponentManager(org.xwiki.component.manager.ComponentManager) DocumentReference(org.xwiki.model.reference.DocumentReference) XWikiConfig(com.xpn.xwiki.XWikiConfig) XWikiException(com.xpn.xwiki.XWikiException)

Example 9 with XWikiServletRequestStub

use of com.xpn.xwiki.web.XWikiServletRequestStub in project xwiki-platform by xwiki.

the class XWikiRequestCopierTest method setup.

@Before
public void setup() throws Exception {
    Utils.setComponentManager(mocker);
    this.originalRequest = new XWikiServletRequestStub();
    this.originalRequest.setHost("host");
    this.originalRequest.setContextPath("contextPath");
    this.originalRequest.setScheme("scheme");
    this.originalRequest.setAttribute("attribute", "value");
    this.originalRequest.setServerName("server");
    this.originalRequest.setrequestURL(new StringBuffer("url"));
}
Also used : XWikiServletRequestStub(com.xpn.xwiki.web.XWikiServletRequestStub) Before(org.junit.Before)

Example 10 with XWikiServletRequestStub

use of com.xpn.xwiki.web.XWikiServletRequestStub in project xwiki-platform by xwiki.

the class SchedulerPlugin method prepareJobStubContext.

/**
 * Create and feed a stub context for the job execution thread. Stub context data are retrieved from job object
 * fields "contextUser", "contextLang", "contextDatabase". If one of this field is empty (this would typically
 * happen on the first schedule operation), it is instead retrieved from the passed context, and the job object is
 * updated with this value. This mean that this method may modify the passed object.
 *
 * @param job the job for which the context will be prepared
 * @param context the XWikiContext at preparation time. This is a real context associated with a servlet request
 * @return the stub context prepared with job data
 */
private XWikiContext prepareJobStubContext(BaseObject job, XWikiContext context) throws SchedulerPluginException {
    boolean jobNeedsUpdate = false;
    String cUser = job.getStringValue("contextUser");
    if (cUser.equals("")) {
        // The context user has not been filled yet.
        // We can suppose it's the first scheduling. Let's assume it's the context user
        cUser = context.getUser();
        job.setStringValue("contextUser", cUser);
        jobNeedsUpdate = true;
    }
    String cLang = job.getStringValue("contextLang");
    if (cLang.equals("")) {
        cLang = context.getLanguage();
        job.setStringValue("contextLang", cLang);
        jobNeedsUpdate = true;
    }
    String iDb = context.getWikiId();
    String cDb = job.getStringValue("contextDatabase");
    if (cDb.equals("") || !cDb.equals(iDb)) {
        cDb = context.getWikiId();
        job.setStringValue("contextDatabase", cDb);
        jobNeedsUpdate = true;
    }
    if (jobNeedsUpdate) {
        try {
            context.setWikiId(cDb);
            XWikiDocument jobHolder = context.getWiki().getDocument(job.getName(), context);
            jobHolder.setMinorEdit(true);
            context.getWiki().saveDocument(jobHolder, context);
        } catch (XWikiException e) {
            throw new SchedulerPluginException(SchedulerPluginException.ERROR_SCHEDULERPLUGIN_UNABLE_TO_PREPARE_JOB_CONTEXT, "Failed to prepare context for job with job name " + job.getStringValue("jobName"), e);
        } finally {
            context.setWikiId(iDb);
        }
    }
    // lets now build the stub context
    XWikiContext scontext = context.clone();
    scontext.setWiki(context.getWiki());
    context.getWiki().getStore().cleanUp(context);
    // We are sure the context request is a real servlet request
    // So we force the dummy request with the current host
    XWikiServletRequestStub dummy = new XWikiServletRequestStub();
    dummy.setHost(context.getRequest().getHeader("x-forwarded-host"));
    dummy.setScheme(context.getRequest().getScheme());
    dummy.setContextPath(context.getRequest().getContextPath());
    XWikiServletRequest request = new XWikiServletRequest(dummy);
    scontext.setRequest(request);
    // Force forged context response to a stub response, since the current context response
    // will not mean anything anymore when running in the scheduler's thread, and can cause
    // errors.
    XWikiResponse stub = new XWikiServletResponseStub();
    scontext.setResponse(stub);
    // feed the dummy context
    scontext.setUser(cUser);
    scontext.setLanguage(cLang);
    scontext.setWikiId(cDb);
    scontext.setMainXWiki(context.getMainXWiki());
    if (scontext.getURL() == null) {
        try {
            scontext.setURL(new URL("http://www.mystuburl.com/"));
        } catch (Exception e) {
        // the URL is well formed, I promise
        }
    }
    com.xpn.xwiki.web.XWikiURLFactory xurf = context.getURLFactory();
    if (xurf == null) {
        xurf = context.getWiki().getURLFactoryService().createURLFactory(context.getMode(), context);
    }
    scontext.setURLFactory(xurf);
    try {
        XWikiDocument cDoc = context.getWiki().getDocument(job.getDocumentReference(), context);
        scontext.setDoc(cDoc);
    } catch (Exception e) {
        throw new SchedulerPluginException(SchedulerPluginException.ERROR_SCHEDULERPLUGIN_UNABLE_TO_PREPARE_JOB_CONTEXT, "Failed to prepare context for job with job name " + job.getStringValue("jobName"), e);
    }
    return scontext;
}
Also used : XWikiServletRequest(com.xpn.xwiki.web.XWikiServletRequest) XWikiServletRequestStub(com.xpn.xwiki.web.XWikiServletRequestStub) XWikiResponse(com.xpn.xwiki.web.XWikiResponse) XWikiContext(com.xpn.xwiki.XWikiContext) URL(java.net.URL) XWikiException(com.xpn.xwiki.XWikiException) SchedulerException(org.quartz.SchedulerException) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiServletResponseStub(com.xpn.xwiki.web.XWikiServletResponseStub) XWikiException(com.xpn.xwiki.XWikiException)

Aggregations

XWikiServletRequestStub (com.xpn.xwiki.web.XWikiServletRequestStub)10 XWikiContext (com.xpn.xwiki.XWikiContext)6 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)6 XWikiServletResponseStub (com.xpn.xwiki.web.XWikiServletResponseStub)5 XWikiServletRequest (com.xpn.xwiki.web.XWikiServletRequest)4 URL (java.net.URL)4 XWiki (com.xpn.xwiki.XWiki)2 XWikiConfig (com.xpn.xwiki.XWikiConfig)2 XWikiException (com.xpn.xwiki.XWikiException)2 XWikiStoreInterface (com.xpn.xwiki.store.XWikiStoreInterface)2 XWikiServletResponse (com.xpn.xwiki.web.XWikiServletResponse)2 XWikiServletURLFactory (com.xpn.xwiki.web.XWikiServletURLFactory)2 Mock (org.jmock.Mock)2 Invocation (org.jmock.core.Invocation)2 CustomStub (org.jmock.core.stub.CustomStub)2 Before (org.junit.Before)2 DocumentReference (org.xwiki.model.reference.DocumentReference)2 JobRequestContext (com.xpn.xwiki.job.JobRequestContext)1 BaseObject (com.xpn.xwiki.objects.BaseObject)1 PropertyClass (com.xpn.xwiki.objects.classes.PropertyClass)1