Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2011 SpringSource
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.codehaus.groovy.grails.plugins.web.api;
 
 
 import java.util.List;
 import java.util.Map;
 
 import  javax.servlet.ServletRequest;
 import  javax.servlet.http.HttpServletRequest;
 import  javax.servlet.http.HttpServletResponse;
 
API for each controller in a Grails application.

Author(s):
Graeme Rocher
Since:
2.0
 
 @SuppressWarnings("rawtypes")
 public class ControllersApi extends CommonWebApi {
 
     private static final String INCLUDE_MAP_KEY = "include";
     private static final String EXCLUDE_MAP_KEY = "exclude";
 
     private static final long serialVersionUID = 1;
 
     protected static final String RENDER_METHOD_NAME = "render";
     protected static final String BIND_DATA_METHOD = "bindData";
     protected static final String SLASH = "/";
     protected transient RedirectDynamicMethod redirect;
     protected transient RenderDynamicMethod render;
     protected transient WithFormMethod withFormMethod;
     protected transient ForwardMethod forwardMethod;
 
     public ControllersApi() {
         this(null);
     }
 
     public ControllersApi(GrailsPluginManager pluginManager) {
         super(pluginManager);
          = new RedirectDynamicMethod();
          = new RenderDynamicMethod();
         = new WithFormMethod();
         = new ForwardMethod();
    }
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (!(requestAttributes instanceof GrailsWebRequest)) {
            return null;
        }
        return ((GrailsWebRequest)requestAttributes).getApplicationContext();
    }
    public void setGspEncoding(String gspEncoding) {
        .setGspEncoding(gspEncoding);
    }
    public void setRedirectListeners(Collection<RedirectEventListenerredirectListeners) {
        .setRedirectListeners(redirectListeners);
    }
    public void setUseJessionId(boolean useJessionId) {
        .setUseJessionId(useJessionId);
    }
    public void setLinkGenerator(LinkGenerator linkGenerator) {
        .setLinkGenerator(linkGenerator);
    }

    
Constructor used by controllers

Parameters:
instance The instance
    public static void initialize(Object instance) {
        ApplicationContext applicationContext = getStaticApplicationContext();
        if (applicationContext == null) {
            return;
        }
        applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(
                instance.false);
        if (Environment.getCurrent() == .) {
            GrailsWebRequest webRequest = GrailsWebRequest.lookup();
            if (webRequest != null) {
                // GRAILS-10929 - If the class name ends with $$..., then it's a proxy and we want to remove that from the name
				String className = instance.getClass().getName().replaceAll("\\$\\$.*$""");
                webRequest.setControllerName(GrailsNameUtils.getLogicalPropertyName(className.));
            }
        }
    }

    
Returns the URI of the currently executing action

Returns:
The action URI
    public String getActionUri(Object instance) {
        return  + getControllerName(instance) +  + getActionName(instance);
    }

    
Returns the URI of the currently executing controller

Returns:
The controller URI
    public String getControllerUri(Object instance) {
        return  + getControllerName(instance);
    }

    
Obtains a URI of a template by name

Parameters:
name The name of the template
Returns:
The template URI
    public String getTemplateUri(Object instanceString name) {
        return getGrailsAttributes(instance).getTemplateUri(namegetRequest(instance));
    }

    
Obtains a URI of a view by name

Parameters:
name The name of the view
Returns:
The template URI
    public String getViewUri(Object instanceString name) {
        return getGrailsAttributes(instance).getViewUri(namegetRequest(instance));
    }

    
Sets the errors instance of the current controller

Parameters:
errors The error instance
    public void setErrors(Object instanceErrors errors) {
    }

    
Obtains the errors instance for the current controller

Returns:
The Errors instance
    public Errors getErrors(Object instance) {
    }

    
Sets the ModelAndView of the current controller

Parameters:
mav The ModelAndView
    public void setModelAndView(Object instanceModelAndView mav) {
    }

    
Obtains the ModelAndView for the currently executing controller

Returns:
The ModelAndView
    public ModelAndView getModelAndView(Object instance) {
    }

    
Obtains the chain model which is used to chain request attributes from one request to the next via flash scope

Returns:
The chainModel
    public Map getChainModel(Object instance) {
        return (Map)getFlash(instance).get("chainModel");
    }

    
Return true if there are an errors

Returns:
true if there are errors
    public boolean hasErrors(Object instance) {
        final Errors errors = getErrors(instance);
        return errors != null && errors.hasErrors();
    }

    
Redirects for the given arguments.

Parameters:
args The arguments
Returns:
null
    public Object redirect(Object instance,Map args) {
        return .invoke(instance"redirect"new Object[]{ args });
    }

    
Redirects for the given arguments.

Parameters:
object A domain class
Returns:
null
    @SuppressWarnings("unchecked")
    public Object redirect(Object instance,Object object) {
        if(object != null) {
            Class<?> objectClass = object.getClass();
            boolean isDomain = DomainClassArtefactHandler.isDomainClass(objectClass) && object instanceof GroovyObject;
            if(isDomain) {
                Object id = ((GroovyObject)object).getProperty(.);
                if(id != null) {
                    Map args = new HashMap();
                    args.put(.object);
                    args.put(...toString());
                    return redirect(instanceargs);
                }
            }
        }
        throw new CannotRedirectException("Cannot redirect for object ["+object+"] it is not a domain or has no identifier. Use an explicit redirect instead ");
    }

    
Invokes the chain method for the given arguments

Parameters:
instance The instance
args The arguments
Returns:
Result of the redirect call
    public Object chain(Object instanceMap args) {
        return ChainMethod.invoke(instanceargs);
    }
    // the render method
    public Object render(Object instanceObject o) {
        return invokeRender(instance, DefaultGroovyMethods.inspect(o));
    }
    public Object render(Object instanceString txt) {
        return invokeRender(instancetxt);
    }
    
    public Object render(Object instanceCharSequence txt) {
        return invokeRender(instancetxt);
    }
    public Object render(Object instanceMap args) {
        return invokeRender(instanceargs);
    }
    public Object render(Object instanceClosure c) {
        return invokeRender(instancec);
    }
    public Object render(Object instanceMap argsClosure c) {
        return invokeRender(instanceargsc);
    }
    public Object render(Object instanceMap argsCharSequence body) {
        return invokeRender(instanceargsbody);
    }
    protected Object invokeRender(Object instanceObject... args) {
        return .invoke(instanceargs);
    }
    public Object bindData(Object instanceObject targetObject bindingSourcefinal List excludes) {
        return bindData(instancetargetbindingSource, CollectionUtils.newMap(excludes), null);
    }
    public Object bindData(Object instanceObject targetObject bindingSourcefinal List excludesString filter) {
        return bindData(instancetargetbindingSource, CollectionUtils.newMap(excludes), filter);
    }
    public Object bindData(Object instanceObject targetObject bindingSourceMap includeExclude) {
        return bindData(instancetargetbindingSourceincludeExcludenull);
    }
    public Object bindData(Object instanceObject targetObject bindingSourceString filter) {
        return bindData(instancetargetbindingSource.filter);
    }
    public Object bindData(Object instanceObject targetObject bindingSource) {
        return bindData(instancetargetbindingSource.null);
    }
    public Object bindData(Object instanceObject targetObject bindingSourceMap includeExcludeString filter) {
        List include = convertToListIfString(includeExclude.get());
        List exclude = convertToListIfString(includeExclude.get());
        DataBindingUtils.bindObjectToInstance(targetbindingSourceincludeexcludefilter);
        return target;
    }
    public <T> void bindData(Object instanceClass<T> targetTypeCollection<T> collectionToPopulate, ServletRequest requestthrows Exception {
        DataBindingUtils.bindToCollection(targetTypecollectionToPopulaterequest);
    }
    public <T> void bindData(Object instanceClass<T> targetTypeCollection<T> collectionToPopulateCollectionDataBindingSource collectionBindingSourcethrows Exception {
        DataBindingUtils.bindToCollection(targetTypecollectionToPopulatecollectionBindingSource);
    }
    @SuppressWarnings("unchecked")
    private List convertToListIfString(Object o) {
        if (o instanceof CharSequence) {
            List list = new ArrayList();
            list.add(o instanceof String ? o : o.toString());
            o = list;
        }
        return (Listo;
    }

    
Sets a response header for the given name and value

Parameters:
instance The instance
headerName The header name
headerValue The header value
    public void header(Object instanceString headerNameObject headerValue) {
        if (headerValue == null) {
            return;
        }
        final HttpServletResponse response = getResponse(instance);
        if (response != null) {
            response.setHeader(headerNameheaderValue.toString());
        }
    }

    
Used the synchronizer token pattern to avoid duplicate form submissions

Parameters:
instance The instance
callable The closure to execute
Returns:
The result of the closure execution
    public Object withForm(Object instanceClosure callable) {
        return .withForm(getWebRequest(instance), callable);
    }

    
Forwards a request for the given parameters using the RequestDispatchers forward method

Parameters:
instance The instance
params The parameters
Returns:
The forwarded URL
    public String forward(Object instanceMap params) {
        return .forward(getRequest(instance), getResponse(instance), params);
    }

    
Initializes a command object. If type is a domain class and the request body or parameters include an id, the id is used to retrieve the command object instance from the database, otherwise the no-arg constructor on type is invoke. If an attempt is made to retrieve the command object instance from the database and no corresponding record is found, null is returned. The command object is then subjected to data binding and dependency injection before being returned.

Parameters:
controllerInstance The controller instance
type The type of the command object
Returns:
the initialized command object or null if the command object is a domain class, the body or parameters included an id and no corresponding record was found in the database.
    public Object initializeCommandObject(final Object controllerInstancefinal Class typefinal String commandObjectParameterNamethrows Exception {
        final HttpServletRequest request = getRequest(controllerInstance);
        Object commandObjectInstance = null;
        
        try {
            final DataBindingSource dataBindingSource = DataBindingUtils
                    .createDataBindingSource(
                            getGrailsApplication(controllerInstance), type,
                            request);
            final DataBindingSource commandObjectBindingSource = WebMetaUtils
                    .getCommandObjectBindingSourceForPrefix(
                            commandObjectParameterNamedataBindingSource);
            Object entityIdentifierValue = null;
            final boolean isDomainClass = DomainClassArtefactHandler
                    .isDomainClass(type);
            if (isDomainClass) {
                entityIdentifierValue = commandObjectBindingSource
                        .getIdentifierValue();
                if (entityIdentifierValue == null) {
                    final GrailsWebRequest webRequest = GrailsWebRequest
                            .lookup(request);
                    entityIdentifierValue = webRequest != null ? webRequest
                            .getParams().getIdentifier() : null;
                }
            }
            if (entityIdentifierValue instanceof String) {
                entityIdentifierValue = ((StringentityIdentifierValue).trim();
                if ("".equals(entityIdentifierValue)
                        || "null".equals(entityIdentifierValue)) {
                    entityIdentifierValue = null;
                }
            }
            final HttpMethod requestMethod = HttpMethod.valueOf(request.getMethod());
            if (entityIdentifierValue != null) {
                try {
                    commandObjectInstance = InvokerHelper.invokeStaticMethod(type"get"entityIdentifierValue);
                } catch (Exception e) {
                    final Errors errors = getErrors(controllerInstance);
                    if (errors != null) {
                        errors.reject(controllerInstance.getClass().getName()
                                + ".commandObject."
                                + commandObjectParameterName + ".error",
                                e.getMessage());
                    }
                }
            } else if (requestMethod == . || !isDomainClass) {
                commandObjectInstance = type.newInstance();
            }
            if (commandObjectInstance != null
                    && commandObjectBindingSource != null) {
                final boolean shouldDoDataBinding;
                if (entityIdentifierValue != null) {
                    switch (requestMethod) {
                    case :
                    case :
                    case :
                        shouldDoDataBinding = true;
                        break;
                    default:
                        shouldDoDataBinding = false;
                    }
                } else {
                    shouldDoDataBinding = true;
                }
                if (shouldDoDataBinding) {
                    bindData(controllerInstancecommandObjectInstancecommandObjectBindingSource.null);
                }
            }
        } catch (Exception e) {
            final Method exceptionHandlerMethodFor = getExceptionHandlerMethodFor(controllerInstancee.getClass());
            if(exceptionHandlerMethodFor != null) {
                throw e;
            }
            commandObjectInstance = type.newInstance();
            final Object o = GrailsMetaClassUtils.invokeMethodIfExists(commandObjectInstance"getErrors");
            if(o instanceof BindingResult) {
                final BindingResult errors = (BindingResult)o;
                String msg = "Error occurred initializing command object [" + commandObjectParameterName + "]. " + e.getMessage();
                ObjectError error = new ObjectError(commandObjectParameterNamemsg);
                errors.addError(error);
            }
        }
        if(commandObjectInstance != null) {
            final ApplicationContext applicationContext = getApplicationContext(controllerInstance);
            final AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
            autowireCapableBeanFactory.autowireBeanProperties(commandObjectInstance.false);
        }
        return commandObjectInstance;
    }
    @SuppressWarnings("unchecked")
    public Method getExceptionHandlerMethodFor(final Object controllerInstancefinal Class<? extends ExceptionexceptionTypethrows Exception {
        if(!Exception.class.isAssignableFrom(exceptionType)) {
            throw new IllegalArgumentException("exceptionType [" + exceptionType.getName() + "] argument must be Exception or a subclass of Exception");
        }
        Method handlerMethod = null;
        final List<ControllerExceptionHandlerMetaDataexceptionHandlerMetaDataInstances = (List<ControllerExceptionHandlerMetaData>) GrailsClassUtils.getStaticFieldValue(controllerInstance.getClass(), .);
        if(exceptionHandlerMetaDataInstances != null && exceptionHandlerMetaDataInstances.size() > 0) {
            // find all of the handler methods which could accept this exception type
            final List<ControllerExceptionHandlerMetaDatamatches = (List<ControllerExceptionHandlerMetaData>) DefaultGroovyMethods.findAll(exceptionHandlerMetaDataInstancesnew Closure(this) {
                @Override
                public Object call(Object object) {
                    ControllerExceptionHandlerMetaData md = (ControllerExceptionHandlerMetaDataobject;
                    return md.getExceptionType().isAssignableFrom(exceptionType);
                }
            });
            if(matches.size() > 0) {
                ControllerExceptionHandlerMetaData theOne = matches.get(0);
                // if there are more than 1, find the one that is farthest down the inheritance hierarchy
                for(int i = 1; i < matches.size(); i++) {
                    final ControllerExceptionHandlerMetaData nextMatch = matches.get(i);
                    if(theOne.getExceptionType().isAssignableFrom(nextMatch.getExceptionType())) {
                        theOne = nextMatch;
                    }
                }
                handlerMethod = controllerInstance.getClass().getMethod(theOne.getMethodName(), theOne.getExceptionType());
            }
        }
        return handlerMethod;
    }
New to GrepCode? Check out our FAQ X