Thursday, January 2, 2020

Request Mocking In Grails For Back-end/Background Threads | Mock Request With Session

Request Mocking In Grails For Back-end/Background Threads | Mock Request With Session

package com.pkm.util

import grails.gsp.PageRenderer
import grails.util.Holders
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest
import org.springframework.web.context.request.RequestContextHolder

import javax.servlet.ServletContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession
/**
 * Created by pritom on 16/08/2017.
 */
class HibernateRequestUtils {
    static GrailsWebRequest getRequest() {
        return RequestContextHolder.getRequestAttributes()
    }

    static HttpSession getSession() {
        return request?.session
    }

    static void setValueToSession(String key, def value) {
        session.putAt(key, value)
    }

    static def getValueFromSession(String key) {
        return session.getAt(key)
    }

    static boolean isBound() {
        HttpServletRequest.isBound()
    }

    static boolean hasSession() {
        session != null
    }

    static def mock(Closure closure = null) {
        return HttpServletRequest.mock(closure)
    }

    static {
        HttpServletRequest.metaClass.static.with {
            isBound = {
                RequestContextHolder.requestAttributes != null
            }
            mock = { closure = null ->
                HttpServletRequest _request = PageRenderer.PageRenderRequestCreator.createInstance("/page/dummy")
                _request.IS_DUMMY = true
                _request."javax.servlet.include.servlet_path" = "/page/dummy.dispatch"
                GrailsWebRequest webRequest = new GrailsWebRequest(
                        _request,
                        PageRenderer.PageRenderResponseCreator.createInstance(new PrintWriter(new StringWriter())),
                        Holders.servletContext
                ) {
                    private MockedHttpSession _session

                    MockedHttpSession getSession() {
                        if (this._session == null) {
                            this._session = new MockedHttpSession()
                        }
                        return this._session
                    }
                }
                RequestContextHolder.setRequestAttributes(webRequest)
                if (closure) {
                    def returned = closure()
                    RequestContextHolder.resetRequestAttributes()
                    return returned
                }
                return webRequest
            }
        }
    }
}

class MockedHttpSession extends GrailsHttpSession {
    MockedHttpSession() {
        super(null)
    }

    private LinkedHashMap attributes = [:]

    Object getAttribute(String name) {
        attributes[name]
    }

    Enumeration getAttributeNames() {
        Collections.enumeration(attributes.keySet())
    }

    long getCreationTime() {
        0
    }

    long getLastAccessedTime() {
        0
    }

    int getMaxInactiveInterval() {
        0
    }

    ServletContext getServletContext() {
        return Holders.servletContext
    }

    @Deprecated
    String[] getValueNames() {
        [] as String[]
    }

    @Deprecated
    void putValue(String name, Object value) {}

    @Deprecated
    void removeValue(String name) {}

    void invalidate() {}

    boolean isNew() {true}

    void removeAttribute(String name) {
        attributes.remove(name)
    }

    void setAttribute(String name, Object value) {
        attributes[name] = value
    }

    void setMaxInactiveInterval(int arg0) {}
}


And use be like below:


if (HibernateRequestUtils.isBound()) {
    DO YOU CODE IN HTTP REQUEST
}
else {
    HibernateRequestUtils.mock {
        DO YOUR CODE IN MOCK REQUEST AS YOU DO IN REAL REQUEST
    }
}



No comments:

Post a Comment