Search in sources :

Example 11 with GrailsWebRequest

use of org.grails.web.servlet.mvc.GrailsWebRequest in project grails-core by grails.

the class WebUtils method clearGrailsWebRequest.

/**
 * Removes any GrailsWebRequest instance from the current request.
 */
public static void clearGrailsWebRequest() {
    RequestAttributes reqAttrs = RequestContextHolder.getRequestAttributes();
    if (reqAttrs != null) {
        // First remove the web request from the HTTP request attributes.
        GrailsWebRequest webRequest = (GrailsWebRequest) reqAttrs;
        webRequest.getRequest().removeAttribute(GrailsApplicationAttributes.WEB_REQUEST);
        // Now remove it from RequestContextHolder.
        RequestContextHolder.resetRequestAttributes();
    }
}
Also used : RequestAttributes(org.springframework.web.context.request.RequestAttributes) GrailsWebRequest(org.grails.web.servlet.mvc.GrailsWebRequest)

Example 12 with GrailsWebRequest

use of org.grails.web.servlet.mvc.GrailsWebRequest in project grails-core by grails.

the class AbstractGrailsView method renderWithinGrailsWebRequest.

private void renderWithinGrailsWebRequest(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    boolean attributesChanged = false;
    try {
        GrailsWebRequest webRequest;
        if (!(requestAttributes instanceof GrailsWebRequest)) {
            webRequest = createGrailsWebRequest(request, response, request.getServletContext());
            attributesChanged = true;
            WebUtils.storeGrailsWebRequest(webRequest);
        } else {
            webRequest = (GrailsWebRequest) requestAttributes;
        }
        renderTemplate(model, webRequest, request, response);
    } finally {
        if (attributesChanged) {
            request.removeAttribute(GrailsApplicationAttributes.WEB_REQUEST);
            RequestContextHolder.setRequestAttributes(requestAttributes);
        }
    }
}
Also used : RequestAttributes(org.springframework.web.context.request.RequestAttributes) GrailsWebRequest(org.grails.web.servlet.mvc.GrailsWebRequest)

Example 13 with GrailsWebRequest

use of org.grails.web.servlet.mvc.GrailsWebRequest in project grails-core by grails.

the class MockGrailsApplication method bindMockHttpRequest.

private GrailsWebRequest bindMockHttpRequest() {
    GrailsMockHttpServletRequest mockRequest = new GrailsMockHttpServletRequest();
    GrailsMockHttpServletResponse mockResponse = new GrailsMockHttpServletResponse();
    GrailsWebRequest webRequest = new GrailsWebRequest(mockRequest, mockResponse, mockRequest.getServletContext());
    mockRequest.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, webRequest);
    RequestContextHolder.setRequestAttributes(webRequest);
    return webRequest;
}
Also used : GrailsMockHttpServletRequest(org.grails.plugins.testing.GrailsMockHttpServletRequest) GrailsWebRequest(org.grails.web.servlet.mvc.GrailsWebRequest) GrailsMockHttpServletResponse(org.grails.plugins.testing.GrailsMockHttpServletResponse)

Example 14 with GrailsWebRequest

use of org.grails.web.servlet.mvc.GrailsWebRequest in project grails-core by grails.

the class MockGrailsApplication method testCodecAndNoCodecGRAILS8405.

@Test
public void testCodecAndNoCodecGRAILS8405() throws IOException {
    FastStringWriter target = new FastStringWriter();
    GrailsWebRequest webRequest = bindMockHttpRequest();
    // Initialize out and codecOut as it is done in GroovyPage.initRun
    OutputEncodingStack outputStack = OutputEncodingStack.currentStack(true, target, false, true);
    GrailsPrintWriter out = outputStack.getOutWriter();
    webRequest.setOut(out);
    GrailsPrintWriter codecOut = new CodecPrintWriter(out, getEncoder(new MockGrailsApplication(), CodecWithClosureProperties.class), registry);
    // print some output
    codecOut.print("hola");
    codecOut.flush();
    out.print("1");
    out.print("2");
    out.print("3");
    // similar as taglib call
    FastStringWriter bufferWriter = new FastStringWriter();
    GrailsPrintWriter out2 = new GrailsPrintWriter(bufferWriter);
    outputStack.push(out2);
    out.print("4");
    codecOut.print("A");
    codecOut.flush();
    outputStack.pop();
    // add output before appending "taglib output"
    out.print("added");
    codecOut.print("too");
    codecOut.flush();
    // append "taglib output"
    out.leftShift(bufferWriter.getBuffer());
    // print some more output
    codecOut.print("B");
    codecOut.flush();
    out.print("5");
    codecOut.print("C");
    codecOut.flush();
    // clear thread local
    RequestContextHolder.resetRequestAttributes();
    assertEquals("-> hola <-123added-> too <-4-> A <--> B <-5-> C <-", target.getValue());
    codecOut.close();
}
Also used : FastStringWriter(org.grails.buffer.FastStringWriter) GrailsPrintWriter(org.grails.buffer.GrailsPrintWriter) GrailsWebRequest(org.grails.web.servlet.mvc.GrailsWebRequest) OutputEncodingStack(org.grails.taglib.encoder.OutputEncodingStack) CodecPrintWriter(org.grails.buffer.CodecPrintWriter) Test(org.junit.Test)

Example 15 with GrailsWebRequest

use of org.grails.web.servlet.mvc.GrailsWebRequest in project grails-core by grails.

the class RegexUrlMapping method createURLInternal.

@SuppressWarnings({ "unchecked" })
private String createURLInternal(Map paramValues, String encoding, boolean includeContextPath) {
    if (encoding == null)
        encoding = "utf-8";
    String contextPath = "";
    if (includeContextPath) {
        GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.getRequestAttributes();
        if (webRequest != null) {
            contextPath = webRequest.getContextPath();
        }
    }
    if (paramValues == null)
        paramValues = Collections.emptyMap();
    StringBuilder uri = new StringBuilder(contextPath);
    Set usedParams = new HashSet();
    String[] tokens = urlData.getTokens();
    int paramIndex = 0;
    for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i];
        if (i == tokens.length - 1 && urlData.hasOptionalExtension()) {
            token += OPTIONAL_EXTENSION_WILDCARD;
        }
        Matcher m = OPTIONAL_EXTENSION_WILDCARD_PATTERN.matcher(token);
        if (m.find()) {
            boolean tokenSet = false;
            if (token.startsWith(CAPTURED_WILDCARD)) {
                ConstrainedProperty prop = constraints[paramIndex++];
                String propName = prop.getPropertyName();
                Object value = paramValues.get(propName);
                usedParams.add(propName);
                if (value != null) {
                    token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), Matcher.quoteReplacement(value.toString()));
                    tokenSet = true;
                } else {
                    token = token.replaceFirst(DOUBLE_WILDCARD_PATTERN.pattern(), "");
                }
            } else {
                tokenSet = true;
            }
            if (tokenSet) {
                uri.append(SLASH);
            }
            ConstrainedProperty prop = constraints[paramIndex++];
            String propName = prop.getPropertyName();
            Object value = paramValues.get(propName);
            usedParams.add(propName);
            if (value != null) {
                String ext = "." + value;
                uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', ext).replace(OPTIONAL_EXTENSION_WILDCARD, ext));
            } else {
                uri.append(token.replace(OPTIONAL_EXTENSION_WILDCARD + '?', "").replace(OPTIONAL_EXTENSION_WILDCARD, ""));
            }
            continue;
        }
        if (token.endsWith("?")) {
            token = token.substring(0, token.length() - 1);
        }
        m = DOUBLE_WILDCARD_PATTERN.matcher(token);
        if (m.find()) {
            StringBuffer buf = new StringBuffer();
            do {
                ConstrainedProperty prop = constraints[paramIndex++];
                String propName = prop.getPropertyName();
                Object value = paramValues.get(propName);
                usedParams.add(propName);
                if (value == null && !prop.isNullable()) {
                    throw new UrlMappingException("Unable to create URL for mapping [" + this + "] and parameters [" + paramValues + "]. Parameter [" + prop.getPropertyName() + "] is required, but was not specified!");
                } else if (value == null) {
                    m.appendReplacement(buf, "");
                } else {
                    m.appendReplacement(buf, Matcher.quoteReplacement(value.toString()));
                }
            } while (m.find());
            m.appendTail(buf);
            try {
                String v = buf.toString();
                if (v.indexOf(SLASH) > -1 && CAPTURED_DOUBLE_WILDCARD.equals(token)) {
                    // individually URL encode path segments
                    if (v.startsWith(SLASH)) {
                        // get rid of leading slash
                        v = v.substring(SLASH.length());
                    }
                    String[] segs = v.split(SLASH);
                    for (String segment : segs) {
                        uri.append(SLASH).append(encode(segment, encoding));
                    }
                } else if (v.length() > 0) {
                    // original behavior
                    uri.append(SLASH).append(encode(v, encoding));
                } else {
                    // Stop processing tokens once we hit an empty one.
                    break;
                }
            } catch (UnsupportedEncodingException e) {
                throw new ControllerExecutionException("Error creating URL for parameters [" + paramValues + "], problem encoding URL part [" + buf + "]: " + e.getMessage(), e);
            }
        } else {
            uri.append(SLASH).append(token);
        }
    }
    populateParameterList(paramValues, encoding, uri, usedParams);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Created reverse URL mapping [" + uri.toString() + "] for parameters [" + paramValues + "]");
    }
    return uri.toString();
}
Also used : Matcher(java.util.regex.Matcher) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlMappingException(grails.web.mapping.exceptions.UrlMappingException) ControllerExecutionException(org.grails.web.servlet.mvc.exceptions.ControllerExecutionException) GrailsWebRequest(org.grails.web.servlet.mvc.GrailsWebRequest) ConstrainedProperty(grails.gorm.validation.ConstrainedProperty)

Aggregations

GrailsWebRequest (org.grails.web.servlet.mvc.GrailsWebRequest)32 Decorator (com.opensymphony.module.sitemesh.Decorator)8 Page (com.opensymphony.module.sitemesh.Page)7 HTMLPageParser (com.opensymphony.module.sitemesh.parser.HTMLPageParser)7 Config (grails.config.Config)7 GroovyObject (groovy.lang.GroovyObject)7 ServletContext (javax.servlet.ServletContext)7 PropertySourcesConfig (org.grails.config.PropertySourcesConfig)7 MockApplicationContext (org.grails.support.MockApplicationContext)7 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)7 MockServletConfig (org.springframework.mock.web.MockServletConfig)7 GroovyClassLoader (groovy.lang.GroovyClassLoader)5 HashMap (java.util.HashMap)5 Map (java.util.Map)4 Binding (groovy.lang.Binding)3 RequestDispatcher (javax.servlet.RequestDispatcher)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 GroovyPageScriptSource (org.grails.gsp.io.GroovyPageScriptSource)2 ControllerExecutionException (org.grails.web.servlet.mvc.exceptions.ControllerExecutionException)2