Example usage for org.apache.wicket.protocol.http.mock MockServletContext MockServletContext

List of usage examples for org.apache.wicket.protocol.http.mock MockServletContext MockServletContext

Introduction

In this page you can find the example usage for org.apache.wicket.protocol.http.mock MockServletContext MockServletContext.

Prototype

public MockServletContext(final Application application, final String path) 

Source Link

Document

Create the mock object.

Usage

From source file:at.molindo.wicketutils.utils.MockUtils.java

License:Apache License

public static WicketFilter newMockFilter(final WebApplication application) {
    final MockServletContext context = new MockServletContext(application, "/");
    final WicketFilter filter = new WicketFilter() {
        @Override//  ww  w  . j a v a2s.  c o  m
        protected IWebApplicationFactory getApplicationFactory() {
            return new IWebApplicationFactory() {
                @Override
                public WebApplication createApplication(WicketFilter filter) {
                    return application;
                }

                @Override
                public void destroy(WicketFilter filter) {
                    // noop
                };
            };
        }
    };

    try {
        filter.init(new FilterConfig() {

            @Override
            public ServletContext getServletContext() {
                return context;
            }

            @Override
            public Enumeration<String> getInitParameterNames() {
                return null;
            }

            @Override
            public String getInitParameter(String name) {
                return null;
            }

            @Override
            public String getFilterName() {
                return "WicketMockServlet";
            }
        });
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }

    return filter;
}

From source file:com.norconex.commons.wicket.ThreadContextMocker.java

License:Apache License

/**
 * Invoke this method in the new thread before doing something with Wicket.
 *//* w  w  w.  ja v  a  2  s.  co m*/
public void mock() {
    ThreadContext.setApplication(application);
    ThreadContext.setSession(session);
    final MockServletContext context = new MockServletContext(application, SystemUtils.JAVA_IO_TMPDIR);
    ThreadContext.setRequestCycle(
            application.createRequestCycle(new MockWebRequest(Url.parse("http://localhost/mock")) {
                @Override
                public Object getContainerRequest() {
                    return new MockHttpServletRequest(application, new MockHttpSession(context), context);
                }
            }, new MockWebResponse()));
}

From source file:com.tysanclan.site.projectewok.TysanPageTester.java

License:Open Source License

@Before
public void startRequest() {
    ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) TysanApplication
            .getApplicationContext().getAutowireCapableBeanFactory();
    // configurableBeanFactory.registerScope("session", new SessionScope());
    configurableBeanFactory.registerScope("request", new RequestScope());
    this.beanFactory = configurableBeanFactory;

    MockServletContext sctx = new MockServletContext(tester.getApplication(), "/src/main/webapp/");
    MockHttpServletRequest request = new MockHttpServletRequest(tester.getApplication(),
            new MockHttpSession(sctx), sctx);
    RequestAttributes attr = new ServletRequestAttributes(request);

    RequestContextHolder.setRequestAttributes(attr);

    sessionFactory = (SessionFactory) configurableBeanFactory.getBean("sessionFactory");

    Session session = sessionFactory.openSession();
    TransactionSynchronizationManager.bindResource(sessionFactory, session);
}

From source file:com.tysanclan.site.projectewok.util.scheduler.TysanTaskExecutor.java

License:Open Source License

/**
 * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
 *///from w  ww .ja  v a2 s. co m
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    TysanTask task = (TysanTask) context.getMergedJobDataMap().get(TASK_KEY);
    TysanApplication application = (TysanApplication) context.getMergedJobDataMap().get(APP_KEY);
    ThreadContext.setApplication(application);

    if (task != null) {
        MockServletContext sctx = new MockServletContext(application, "/src/main/webapp/");
        MockHttpServletRequest request = new MockHttpServletRequest(application, new MockHttpSession(sctx),
                sctx);
        RequestAttributes attr = new ServletRequestAttributes(request);

        RequestContextHolder.setRequestAttributes(attr);
        Injector.get().inject(task);
        try {
            task.run();
        } catch (Exception e) {
            BugTrackerService tracker = TysanApplication.getApplicationContext()
                    .getBean(BugTrackerService.class);
            if (!tracker.isKnownIssue(e)) {
                tracker.reportCrash(null, task.getClass().getName(), e);
            }
        }
        task.cleanUp();
        RequestContextHolder.resetRequestAttributes();
    } else {
        logger.error("No task passed to TysanTaskExecutor!");
    }
}

From source file:dk.frankbille.scoreboard.test.WicketSpringTestCase.java

License:Open Source License

@BeforeClass
public static void setupSpring() {
    if (applicationContext == null) {
        MockServletContext servletContext = new MockServletContext(new ScoreBoardApplication(),
                "src/main/webapp");
        servletContext.addInitParameter("contextConfigLocation", "classpath:applicationContext-test.xml");
        ContextLoader loader = new ContextLoader();
        applicationContext = loader.initWebApplicationContext(servletContext);
        WicketSpringTestCase.servletContext = servletContext;
    }/*from   ww  w .  j  ava2  s .  co  m*/
}

From source file:org.apache.openmeetings.db.util.ApplicationHelper.java

License:Apache License

public static IApplication ensureApplication(Long langId) {
    IApplication a = null;/*ww w.  ja  va 2 s .  c o m*/
    if (Application.exists()) {
        a = (IApplication) Application.get();
    } else {
        WebApplication app = (WebApplication) Application.get(wicketApplicationName);
        LabelDao.initLanguageMap();
        if (app == null) {
            try {
                app = (WebApplication) LabelDao.getAppClass().newInstance();
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                log.error("Failed to create Application");
                return null;
            }
            app.setServletContext(new MockServletContext(app, null));
            app.setName(wicketApplicationName);
            ServletContext sc = app.getServletContext();
            OMContextListener omcl = new OMContextListener();
            omcl.contextInitialized(new ServletContextEvent(sc));
            XmlWebApplicationContext xmlContext = new XmlWebApplicationContext();
            xmlContext.setConfigLocation("classpath:openmeetings-applicationContext.xml");
            xmlContext.setServletContext(sc);
            xmlContext.refresh();
            sc.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, xmlContext);
            app.setConfigurationType(RuntimeConfigurationType.DEPLOYMENT);
            ThreadContext.setApplication(app);
            app.initApplication();
        } else {
            ThreadContext.setApplication(app);
        }
        a = (IApplication) Application.get(wicketApplicationName);
    }
    if (ThreadContext.getRequestCycle() == null) {
        ServletWebRequest req = new ServletWebRequest(new MockHttpServletRequest((Application) a,
                new MockHttpSession(a.getServletContext()), a.getServletContext()), "");
        RequestCycleContext rctx = new RequestCycleContext(req, new MockWebResponse(), a.getRootRequestMapper(),
                a.getExceptionMapperProvider().get());
        ThreadContext.setRequestCycle(new RequestCycle(rctx));
    }
    if (ThreadContext.getSession() == null) {
        WebSession s = WebSession.get();
        if (langId > 0) {
            ((IWebSession) s).setLanguage(langId);
        }
    }
    return a;
}

From source file:org.artifactory.webapp.wicket.page.admin.AbstractWicketTest.java

License:Open Source License

@BeforeClass
public void setUp() throws Exception {
    //Creates a new application context mock.
    applicationContextMock = new ApplicationContextMock();

    artifactoryHomeBoundTest = new ArtifactoryHomeBoundTest();
    artifactoryHomeBoundTest.bindArtifactoryHome();

    dummyArtifactoryContext = new DummyArtifactoryContext(applicationContextMock);
    ArtifactoryContextThreadBinder.bind(dummyArtifactoryContext);

    configService = mock(CentralConfigService.class);
    when(configService.getVersionInfo()).thenReturn(new VersionInfo(
            ConstantValues.artifactoryVersion.getString(), ConstantValues.artifactoryRevision.getString()));
    CentralConfigDescriptorImpl configDescriptor = new CentralConfigDescriptorImpl();
    configDescriptor.setFooter("bla");
    when(configService.getDescriptor()).thenReturn(configDescriptor);
    addMock("centralConfig", configService);

    AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
    //For authentication, use mock like this:
    //Authentication authentication = mock(Authentication.class);
    //when(authentication.isAuthenticated()).thenReturn(true);
    //when(authentication.getPrincipal()).thenReturn("admin");
    //when(authentication.getAuthorities()).thenReturn(SimpleUser.ADMIN_GAS);

    //or real authentication like this:
    //((ArtifactoryWebSession) getTester().getSession()).signIn("admin", "password");
    when(authenticationManager.authenticate(any(Authentication.class)))
            .thenReturn(new SystemAuthenticationToken());
    addMock("authenticationManager", authenticationManager);

    AddonsManager addonsManager = mock(AddonsManager.class);
    when(addonsManager.isInstantiationAuthorized((Class) notNull())).thenReturn(true);
    when(addonsManager.addonByType(WebApplicationAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(SearchAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(PropertiesWebAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(LicensesWebAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(BlackDuckWebAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(HaWebAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(CrowdWebAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(SamlWebAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(HttpSsoAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(WebstartWebAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.addonByType(SamlAddon.class)).thenReturn(new WicketAddonsImpl());
    when(addonsManager.isLicenseInstalled()).thenReturn(true);
    when(addonsManager.addonByType(HaCommonAddon.class)).thenReturn(new CoreAddonsImpl());
    addMock("addonsManager", addonsManager);

    AuthorizationService authorizationService = mock(AuthorizationService.class);
    when(authorizationService.isAnonymous()).thenReturn(false);
    when(authorizationService.isAdmin()).thenReturn(true);
    addMock("authorizationService", authorizationService);

    AddonsWebManager addonsWebManager = mock(AddonsWebManager.class);
    addMock("AddonsWebManager", addonsWebManager);

    ArtifactoryServersCommonService serversCommonService = mock(ArtifactoryServersCommonService.class);
    addMock("serversService", serversCommonService);

    SecurityService securityService = mock(SecurityService.class);
    when(securityService.getUserLastLoginInfo("admin")).thenReturn(null);
    addMock("securityService", securityService);

    StorageService storageService = mock(StorageService.class);
    when(storageService.getStorageQuotaInfo(0)).thenReturn(null);
    addMock("storageService", storageService);

    //Creates a new WicketTester
    ArtifactoryApplication application = new ArtifactoryApplication();
    MockServletContext servletContext = new MockServletContext(application, null);
    servletContext.setAttribute(ArtifactoryContext.APPLICATION_CONTEXT_KEY, ContextHelper.get());
    tester = new WicketTester(application, servletContext);

    setupTest();//from ww w  . ja va 2s. c  o  m
}

From source file:org.hippoecm.frontend.plugin.config.impl.JcrConfigServiceFactoryTest.java

License:Apache License

@Test
public void testFirstApplicationIsUsedAsFallback() throws Exception {
    PluginTestApplication secondApp = new PluginTestApplication();
    MockServletContext servletContext = new MockServletContext(secondApp, null);
    servletContext.addInitParameter("config", "second-app");
    HippoTester second = new HippoTester(secondApp, servletContext);

    try {/*from  w  w w.j a v a2  s  . co  m*/
        PluginPage home = (PluginPage) second.startPluginPage();
        JavaPluginConfig config = new JavaPluginConfig("dummy");
        config.put("plugin.class", DummyPlugin.class.getName());
        IPluginContext context = home.getPluginManager().start(config);
        IPluginConfigService pcs = context.getService(IPluginConfigService.class.getName(),
                IPluginConfigService.class);
        IClusterConfig cluster = pcs.getCluster("service");
        assertEquals(new JcrClusterConfig(new JcrNodeModel("/config/test-app/service")), cluster);
    } finally {
        second.destroy();
    }
}

From source file:org.wicketstuff.jeeweb.JEEWebResolverTest.java

License:Apache License

@Test
public void testServletsAndJSPsAreResolvedRight() throws Exception {
    TestApplication testApplication = new TestApplication();
    MockServletContext mockServletContext = new MockServletContext(testApplication,
            new File("src/test/webapp").getCanonicalPath());

    mockServletContext.addServlet("/TestServlet", new HttpServlet() {
    });/*  w w w.j a  va  2  s.  com*/

    WicketTester wicketTester = new WicketTester(testApplication, mockServletContext);
    wicketTester.startPage(TestServletAndJSPPage.class);
    String lastResponse = wicketTester.getLastResponseAsString();
    Assert.assertTrue(lastResponse.contains("INCLUDE OF RESOURCE: /TestServlet"));
    Assert.assertTrue(lastResponse.contains("INCLUDE OF RESOURCE: /TestJSP.jsp"));
}

From source file:org.wicketstuff.jeeweb.JEEWebResolverTest.java

License:Apache License

@Test(expected = org.apache.wicket.WicketRuntimeException.class)
public void testJSPRequestIsFailingIfNotExist() throws Exception {
    TestApplication testApplication = new TestApplication();
    MockServletContext mockServletContext = new MockServletContext(testApplication,
            new File("src/main/webapp").getCanonicalPath());
    WicketTester wicketTester = new WicketTester(testApplication, mockServletContext);
    wicketTester.startPage(TestJSPFailPage.class);
}