Example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

List of usage examples for org.springframework.web.context.request RequestContextHolder currentRequestAttributes

Introduction

In this page you can find the example usage for org.springframework.web.context.request RequestContextHolder currentRequestAttributes.

Prototype

public static RequestAttributes currentRequestAttributes() throws IllegalStateException 

Source Link

Document

Return the RequestAttributes currently bound to the thread.

Usage

From source file:org.codehaus.groovy.grails.scaffolding.DefaultScaffoldRequestHandler.java

private Serializable getRequestId() {
    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
    return (Serializable) webRequest.getParams().get(PARAM_ID);
}

From source file:org.codehaus.groovy.grails.scaffolding.DefaultScaffoldRequestHandler.java

public Map handleSave(HttpServletRequest request, HttpServletResponse reponse, ScaffoldCallback callback) {

    Object domainObject = domain.newInstance();
    WebRequest webRequest = (WebRequest) RequestContextHolder.currentRequestAttributes();
    InvokerHelper.setProperty(domainObject, "properties", webRequest.getParameterMap());

    Errors domainObjectErrors = (Errors) InvokerHelper.getProperty(domainObject, "errors");

    Map model = new HashMap();
    model.put(domain.getSingularName(), domainObject);

    if (!domainObjectErrors.hasErrors() && this.domain.save(domainObject, callback)) {
        BeanWrapper domainBean = new BeanWrapperImpl(domainObject);
        Object identity = domainBean.getPropertyValue(domain.getIdentityPropertyName());
        model.put(PARAM_ID, identity);//  ww  w . j a  va 2 s .  c  o  m
        callback.setInvoked(true);
    }
    return model;
}

From source file:org.codehaus.groovy.grails.scaffolding.DefaultScaffoldRequestHandler.java

public Map handleUpdate(HttpServletRequest request, HttpServletResponse reponse, ScaffoldCallback callback) {
    Serializable id = getRequestId();
    if (id == null) {
        LOG.debug("[ScaffoldRequestHandler] No ID parameter [" + id + "] for request [update]");
        callback.setInvoked(false);//from w w  w.ja va2 s.c om
        return Collections.EMPTY_MAP;
    }

    Object domainObject = this.domain.get(id);
    WebRequest webRequest = (WebRequest) RequestContextHolder.currentRequestAttributes();
    InvokerHelper.setProperty(domainObject, "properties", webRequest.getParameterMap());

    Errors domainObjectErrors = (Errors) InvokerHelper.getProperty(domainObject, "errors");

    Map model = new HashMap();
    model.put(this.domain.getSingularName(), domainObject);
    model.put(PARAM_ID, id);
    // execute update
    if (!domainObjectErrors.hasErrors() && this.domain.update(domainObject, callback)) {
        callback.setInvoked(true);
    } else {
        callback.setInvoked(false);
    }
    return model;
}

From source file:org.codehaus.groovy.grails.web.mapping.RegexUrlMapping.java

/**
 * This method will look for a constraint for the given name and return a closure that when executed will
 * attempt to evaluate its value from the bound request parameters at runtime.
 *
 * @param name        The name of the constrained property
 * @param constraints The array of current ConstrainedProperty instances
 * @return Either a Closure or null/*  w ww  . j a  va 2 s .  co m*/
 */
private Object createRuntimeConstraintEvaluator(final String name, ConstrainedProperty[] constraints) {
    if (constraints == null)
        return null;

    for (ConstrainedProperty constraint : constraints) {
        if (constraint.getPropertyName().equals(name)) {
            return new Closure(this) {
                private static final long serialVersionUID = -2404119898659287216L;

                @Override
                public Object call(Object... objects) {
                    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder
                            .currentRequestAttributes();
                    return webRequest.getParams().get(name);
                }
            };
        }
    }
    return null;
}

From source file:org.codehaus.groovy.grails.web.metaclass.RedirectDynamicMethod.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//ww  w . j a  va 2  s .c om
public Object invoke(Object target, String methodName, Object[] arguments) {
    if (arguments.length == 0) {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }

    Map argMap = arguments[0] instanceof Map ? (Map) arguments[0] : Collections.EMPTY_MAP;
    if (argMap.isEmpty()) {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }

    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
    LinkGenerator requestLinkGenerator = getLinkGenerator(webRequest);

    HttpServletRequest request = webRequest.getCurrentRequest();
    if (request.getAttribute(GRAILS_REDIRECT_ISSUED) != null) {
        throw new CannotRedirectException(
                "Cannot issue a redirect(..) here. A previous call to redirect(..) has already redirected the response.");
    }

    HttpServletResponse response = webRequest.getCurrentResponse();
    if (response.isCommitted()) {
        throw new CannotRedirectException(
                "Cannot issue a redirect(..) here. The response has already been committed either by another redirect or by directly writing to the response.");
    }

    if (target instanceof GroovyObject) {
        GroovyObject controller = (GroovyObject) target;

        // if there are errors add it to the list of errors
        Errors controllerErrors = (Errors) controller.getProperty(ControllerDynamicMethods.ERRORS_PROPERTY);
        Errors errors = (Errors) argMap.get(ARGUMENT_ERRORS);
        if (controllerErrors != null && errors != null) {
            controllerErrors.addAllErrors(errors);
        } else {
            controller.setProperty(ControllerDynamicMethods.ERRORS_PROPERTY, errors);
        }
        Object action = argMap.get(GrailsControllerClass.ACTION);
        if (action != null) {
            argMap.put(GrailsControllerClass.ACTION, establishActionName(action, controller));
        }
        if (!argMap.containsKey(GrailsControllerClass.NAMESPACE_PROPERTY)) {
            // this could be made more efficient if we had a reference to the GrailsControllerClass object, which
            // has the namespace property accessible without needing reflection
            argMap.put(GrailsControllerClass.NAMESPACE_PROPERTY, GrailsClassUtils
                    .getStaticFieldValue(controller.getClass(), GrailsControllerClass.NAMESPACE_PROPERTY));
        }
    }
    boolean permanent = DefaultGroovyMethods.asBoolean(argMap.get(ARGUMENT_PERMANENT));

    // we generate a relative link with no context path so that the absolute can be calculated by combining the serverBaseURL
    // which includes the contextPath
    argMap.put(LinkGenerator.ATTRIBUTE_CONTEXT_PATH, BLANK);

    return redirectResponse(requestLinkGenerator.getServerBaseURL(), requestLinkGenerator.link(argMap), request,
            response, permanent);
}

From source file:org.codehaus.groovy.grails.web.metaclass.RedirectDynamicMethod.java

/**
 * getter to obtain RequestDataValueProcessor from
 *///  w ww .  j  ava  2s . c  o m
private void initRequestDataValueProcessor() {
    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
    ApplicationContext applicationContext = webRequest.getApplicationContext();
    if (requestDataValueProcessor == null && applicationContext.containsBean("requestDataValueProcessor")) {
        requestDataValueProcessor = applicationContext.getBean("requestDataValueProcessor",
                RequestDataValueProcessor.class);
    }
}

From source file:org.codehaus.groovy.grails.web.metaclass.RenderDynamicMethod.java

@Override
public Object invoke(Object target, String methodName, Object[] arguments) {
    if (arguments.length == 0) {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }//from  ww w.j a va 2  s. c  o  m

    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
    HttpServletResponse response = webRequest.getCurrentResponse();

    boolean renderView = true;
    GroovyObject controller = (GroovyObject) target;
    if (arguments[0] instanceof CharSequence) {
        setContentType(response, TEXT_HTML, DEFAULT_ENCODING, true);
        CharSequence text = (CharSequence) arguments[0];
        renderView = renderText(text, response);
    } else if (arguments[0] instanceof Closure) {
        setContentType(response, TEXT_HTML, gspEncoding, true);
        Closure closure = (Closure) arguments[arguments.length - 1];
        renderView = renderMarkup(closure, response);
    } else if (arguments[0] instanceof Map) {
        Map argMap = (Map) arguments[0];
        boolean hasContentType = argMap.containsKey(ARGUMENT_CONTENT_TYPE);

        Writer out = null;
        if (hasContentType) {
            out = getWriterForConfiguredContentType(response, argMap, hasContentType);
            webRequest.setOut(out);
        }
        if (argMap.containsKey(ARGUMENT_LAYOUT)) {
            webRequest.getCurrentRequest().setAttribute(GrailsLayoutDecoratorMapper.LAYOUT_ATTRIBUTE,
                    argMap.get(ARGUMENT_LAYOUT));
        }

        boolean statusSet = false;
        if (argMap.containsKey(ARGUMENT_STATUS)) {
            Object statusObj = argMap.get(ARGUMENT_STATUS);
            if (statusObj != null) {
                try {
                    response.setStatus(Integer.parseInt(statusObj.toString()));
                    statusSet = true;
                } catch (NumberFormatException e) {
                    throw new ControllerExecutionException(
                            "Argument [status] of method [render] must be a valid integer.");
                }
            }
        }

        if (arguments[arguments.length - 1] instanceof Closure) {
            Closure callable = (Closure) arguments[arguments.length - 1];
            if (BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER)) || isJSONResponse(response)) {
                renderView = renderJSON(callable, response);
            } else {
                renderView = renderMarkup(callable, response);
            }
        } else if (arguments[arguments.length - 1] instanceof CharSequence) {
            if (out == null) {
                out = getWriterForConfiguredContentType(response, argMap, hasContentType);
                webRequest.setOut(out);
            }

            CharSequence text = (CharSequence) arguments[arguments.length - 1];
            renderView = renderText(text, out);
        } else if (argMap.containsKey(ARGUMENT_TEXT)) {
            if (out == null) {
                out = getWriterForConfiguredContentType(response, argMap, hasContentType);
                webRequest.setOut(out);
            }

            Object textArg = argMap.get(ARGUMENT_TEXT);
            CharSequence text = (textArg instanceof CharSequence) ? ((CharSequence) textArg)
                    : textArg.toString();
            renderView = renderText(text, out);
        } else if (argMap.containsKey(ARGUMENT_VIEW)) {
            renderView(webRequest, argMap, target, controller, hasContentType);
        } else if (argMap.containsKey(ARGUMENT_TEMPLATE)) {
            if (out == null) {
                out = getWriterForConfiguredContentType(response, argMap, hasContentType);
                webRequest.setOut(out);
            }

            renderView = renderTemplate(target, controller, webRequest, argMap, out);
        } else if (argMap.containsKey(ARGUMENT_FILE)) {
            renderView = false;

            Object o = argMap.get(ARGUMENT_FILE);
            Object fnO = argMap.get(ARGUMENT_FILE_NAME);
            String fileName = fnO != null ? fnO.toString()
                    : ((o instanceof File) ? ((File) o).getName() : null);
            if (o != null) {
                if (fileName != null) {
                    detectContentTypeFromFileName(webRequest, response, argMap, fileName, hasContentType);
                    if (fnO != null) {
                        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                                DISPOSITION_HEADER_PREFIX + fileName);
                    }
                } else if (!hasContentType) {
                    throw new ControllerExecutionException(
                            "Argument [file] of render method specified without valid [contentType] argument");
                }

                InputStream input = null;
                try {
                    if (o instanceof File) {
                        File f = (File) o;
                        input = FileUtils.openInputStream(f);
                    } else if (o instanceof InputStream) {
                        input = (InputStream) o;
                    } else if (o instanceof byte[]) {
                        input = new ByteArrayInputStream((byte[]) o);
                    } else {
                        input = FileUtils.openInputStream(new File(o.toString()));
                    }
                    IOUtils.copy(input, response.getOutputStream());
                } catch (IOException e) {
                    throw new ControllerExecutionException(
                            "I/O error copying file to response: " + e.getMessage(), e);

                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                }
            }
        } else if (statusSet) {
            // GRAILS-6711 nothing to render, just setting status code, so don't render the map
            renderView = false;
        } else {
            Object object = arguments[0];
            if (object instanceof JSONElement) {
                renderView = renderJSON((JSONElement) object, response);
            } else {
                out = getWriterForConfiguredContentType(response, argMap, hasContentType);
                webRequest.setOut(out);

                renderView = renderObject(object, out);
            }
        }
        try {
            if (!renderView) {
                if (out != null) {
                    out.flush();
                }
            }
        } catch (IOException e) {
            throw new ControllerExecutionException(
                    "I/O error executing render method for arguments [" + argMap + "]: " + e.getMessage(), e);
        }
    } else {
        throw new MissingMethodException(METHOD_SIGNATURE, target.getClass(), arguments);
    }
    webRequest.setRenderView(renderView);
    return null;
}

From source file:org.codehaus.groovy.grails.web.pages.ext.jsp.GroovyPagesPageContext.java

public GroovyPagesPageContext(Servlet pagesServlet, Binding pageScope) {
    Assert.notNull(pagesServlet, "GroovyPagesPageContext class requires a reference to the GSP servlet");
    webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();

    servletContext = webRequest.getServletContext();
    request = webRequest.getCurrentRequest();
    response = webRequest.getCurrentResponse();
    servlet = pagesServlet;//ww w .j a v a 2s . c om
    servletconfig = pagesServlet.getServletConfig();
    this.pageScope = pageScope;
    session = request.getSession(false);
    // setup initial writer
    pushWriter(new JspWriterDelegate(webRequest.getOut()));
    // Register page attributes as per JSP spec
    setAttribute(REQUEST, request);
    setAttribute(RESPONSE, response);
    if (session != null) {
        setAttribute(SESSION, session);
    }
    setAttribute(PAGE, servlet);
    setAttribute(CONFIG, servlet.getServletConfig());
    setAttribute(PAGECONTEXT, this);
    setAttribute(APPLICATION, servletContext);
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageOutputStack.java

public static final void removeCurrentInstance() {
    RequestContextHolder.currentRequestAttributes().removeAttribute(ATTRIBUTE_NAME_OUTPUT_STACK,
            RequestAttributes.SCOPE_REQUEST);
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPagesServlet.java

/**
 * Creates a response writer for the given response object
 *
 * @param response The HttpServletResponse
 * @return The created java.io.Writer//  w  ww  .  j  a  va2 s .  c  o m
 */
protected GSPResponseWriter createResponseWriter(HttpServletResponse response) {
    GSPResponseWriter out = GSPResponseWriter.getInstance(response);
    GrailsWebRequest webRequest = (GrailsWebRequest) RequestContextHolder.currentRequestAttributes();
    webRequest.setOut(out);
    return out;
}