Example usage for org.apache.wicket ThreadContext restore

List of usage examples for org.apache.wicket ThreadContext restore

Introduction

In this page you can find the example usage for org.apache.wicket ThreadContext restore.

Prototype

public static void restore(ThreadContext threadContext) 

Source Link

Document

Restores the context

Usage

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

License:Apache License

/**
 * unset request and session to force mocking
 *//*from ww  w  . ja v  a2s  .com*/
public static <V> V withNewRequest(WebApplication webApplication, IMockRequestCallback<V> callback) {
    ThreadContext oldContext = ThreadContext.detach();
    try {
        return withRequest(webApplication, callback);
    } finally {
        ThreadContext.restore(oldContext);
    }
}

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

License:Apache License

/**
 * reuse an existing session if possible
 *///from  w  ww .j  a  va  2s . c  o  m
public static <V> V withRequest(WebApplication webApplication, IMockRequestCallback<V> callback) {
    Session oldSession = ThreadContext.exists() ? ThreadContext.getSession() : null;
    ThreadContext oldContext = ThreadContext.detach();

    try {
        ThreadContext.setApplication(webApplication);
        ThreadContext.setSession(oldSession);

        // mock http session
        ServletContext context = webApplication.getServletContext();
        MockHttpSession httpSession = new MockHttpSession(context);

        // mock servlet request
        MockServletRequest servletRequest = new MockServletRequest(webApplication, httpSession, context);
        callback.configure(new MockRequest(servletRequest));
        servletRequest.setDefaultHeaders();

        // mock response
        MockHttpServletResponse servletResponse = new MockHttpServletResponse(servletRequest);

        // mock web request
        final WebRequest request = VisibilityHelper.newWebRequest(webApplication, servletRequest, "/");

        // mock web response
        final WebResponse response = VisibilityHelper.newWebResponse(webApplication, request, servletResponse);

        // create
        ThreadContext.setRequestCycle(webApplication.createRequestCycle(request, response));

        return callback.call();
    } finally {
        Session newSession = ThreadContext.getSession();
        ThreadContext.restore(oldContext);
        if (oldSession == null && newSession != null && !newSession.isTemporary()) {
            // reuse session if a new one was created
            ThreadContext.setSession(newSession);
        }
    }
}