Example usage for org.springframework.web.bind ServletRequestDataBinder ServletRequestDataBinder

List of usage examples for org.springframework.web.bind ServletRequestDataBinder ServletRequestDataBinder

Introduction

In this page you can find the example usage for org.springframework.web.bind ServletRequestDataBinder ServletRequestDataBinder.

Prototype

public ServletRequestDataBinder(@Nullable Object target, String objectName) 

Source Link

Document

Create a new ServletRequestDataBinder instance.

Usage

From source file:no.abmu.abmstatistikk.web.AbstractStatusBrowsingController.java

/**
 * Refreshable status browser. /* ww w  . ja  va 2  s . c  o m*/
 * @param request current HTTP request
 * @param attribute to use store RefreshablePageholder in current http session
 * @param organisationType name of organisation type
 * @param schemaType name of schema type
 * @param view - if sucess use this view as view in ModelAndView
 * @param year - report year
 * @return a ModelAndView to render the response
 */
/*
    protected ModelAndView countyStatusBrowser(
    HttpServletRequest request, 
    String attribute,
    String organisationType, 
    String schemaType,
    String view,
    int year) {
        
// This should be replaced with AOP in an XML spring config-file.
if (!isSecureContext()) {
    logger.error("[refreshableCountyStatusBrowser]: no secureContext loging off");
    return new ModelAndView(ViewNameConst.LOGOFF_VIEW);
}
        
Integer countyNumber = getCountyNumberFromRequestOrLoggedOnUser(request);
if (null == countyNumber) {
    logger.error("[countyStatusBrowser]: could not get any countynumber, return to mainmenu.");
    return new ModelAndView(ViewNameConst.REDIRECT_2_MAIN_MENU);
}
        
OrgUnitFinderSpecificationBean finderBean = new OrgUnitFinderSpecificationBean();
finderBean.setOrganisationTypeName(organisationType);
finderBean.setCountyNumber(countyNumber);
finderBean.setTodayAsActiveDate();
        
Map model = statusBrowse(request, attribute, finderBean, schemaType,  year);
        
return new ModelAndView(view, model);
    }    
            
*/

// ////////////////////////////////////////////////////////////////////////
//
// Private methods for status browsing
//
// ////////////////////////////////////////////////////////////////////////

protected Map<String, Object> statusBrowse(HttpServletRequest request, String attribute,
        OrgUnitFinderSpecificationBean finderBean, SchemaTypeNameAndVersion schemaTypeNameAndVersion) {

    logger.info("Executing statusBrowse");

    PageHolder pageHolder = (PageHolder) request.getSession(true).getAttribute(attribute);

    if (null == pageHolder) {
        pageHolder = statusReportService.createNewPageHolder(finderBean, schemaTypeNameAndVersion);
        request.getSession().setAttribute(attribute, pageHolder);
    }

    ServletRequestDataBinder binder = new ServletRequestDataBinder(pageHolder, "pageHolder");
    binder.bind(request);
    pageHolder.reload(false);

    return binder.getBindingResult().getModel();

}

From source file:org.codehaus.enunciate.modules.rest.RESTResourceExporter.java

/**
 * Handles a specific REST operation.// ww w .  jav a  2  s. c  o  m
 *
 * @param operation The operation.
 * @param handler   The handler for the operation.
 * @param request   The request.
 * @param response  The response.
 * @return The model and view.
 */
protected ModelAndView handleRESTOperation(RESTOperation operation, RESTRequestContentTypeHandler handler,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (!this.endpoints.containsKey(operation.getVerb())) {
        throw new MethodNotAllowedException("Method not allowed.");
    }

    if ((this.multipartRequestHandler != null) && (this.multipartRequestHandler.isMultipart(request))) {
        request = this.multipartRequestHandler.handleMultipartRequest(request);
    }

    String requestContext = request.getRequestURI().substring(request.getContextPath().length());
    Map<String, String> contextParameters;
    try {
        contextParameters = resource.getContextParameterAndProperNounValues(requestContext);
    } catch (IllegalArgumentException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return null;
    }

    Object properNounValue = null;
    HashMap<String, Object> contextParameterValues = new HashMap<String, Object>();
    for (Map.Entry<String, String> entry : contextParameters.entrySet()) {
        String parameterName = entry.getKey();
        String parameterValue = entry.getValue();
        if (parameterName == null) {
            Class nounType = operation.getProperNounType();
            if (nounType != null) {
                //todo: provide a hook to some other conversion mechanism?
                try {
                    properNounValue = converter.convert(parameterValue, nounType);
                } catch (Exception e) {
                    throw new ParameterConversionException(parameterValue);
                }
            }
        } else {
            Class contextParameterType = operation.getContextParameterTypes().get(parameterName);
            if (contextParameterType != null) {
                //todo: provide a hook to some other conversion mechanism?
                try {
                    contextParameterValues.put(parameterName,
                            converter.convert(parameterValue, contextParameterType));
                } catch (Exception e) {
                    throw new ParameterConversionException(parameterValue);
                }
            }
        }
    }

    if ((properNounValue == null) && (operation.isProperNounOptional() != null)
            && (!operation.isProperNounOptional())) {
        throw new MissingParameterException(
                "A specific '" + resource.getNoun() + "' must be specified on the URL.");
    }

    HashMap<String, Object> adjectives = new HashMap<String, Object>();
    for (String adjective : operation.getAdjectiveTypes().keySet()) {
        Object adjectiveValue = null;

        if (!operation.getComplexAdjectives().contains(adjective)) {
            //not complex, map it.
            String[] parameterValues = request.getParameterValues(adjective);
            if ((parameterValues != null) && (parameterValues.length > 0)) {
                //todo: provide a hook to some other conversion mechanism?
                final Class adjectiveType = operation.getAdjectiveTypes().get(adjective);
                Class componentType = adjectiveType.isArray() ? adjectiveType.getComponentType()
                        : adjectiveType;
                Object adjectiveValues = Array.newInstance(componentType, parameterValues.length);
                for (int i = 0; i < parameterValues.length; i++) {
                    try {
                        Array.set(adjectiveValues, i, converter.convert(parameterValues[i], componentType));
                    } catch (Exception e) {
                        throw new KeyParameterConversionException(adjective, parameterValues[i]);
                    }
                }

                if (adjectiveType.isArray()) {
                    adjectiveValue = adjectiveValues;
                } else {
                    adjectiveValue = Array.get(adjectiveValues, 0);
                }
            }

            if ((adjectiveValue == null) && (!operation.getAdjectivesOptional().get(adjective))) {
                throw new MissingParameterException("Missing request parameter: " + adjective);
            }
        } else {
            //use spring's binding to map the complex adjective to the request parameters.
            try {
                adjectiveValue = operation.getAdjectiveTypes().get(adjective).newInstance();
            } catch (Throwable e) {
                throw new IllegalArgumentException(
                        "A complex adjective must have a simple, no-arg constructor. Invalid type: "
                                + operation.getAdjectiveTypes().get(adjective));
            }

            ServletRequestDataBinder binder = new ServletRequestDataBinder(adjectiveValue, adjective);
            binder.setIgnoreUnknownFields(true);
            binder.bind(request);
            BindException errors = binder.getErrors();
            if ((errors != null) && (errors.getAllErrors() != null) && (!errors.getAllErrors().isEmpty())) {
                ObjectError firstError = (ObjectError) errors.getAllErrors().get(0);
                String message = "Invalid parameter.";
                if (firstError instanceof FieldError) {
                    throw new ParameterConversionException(
                            ((FieldError) firstError).getRejectedValue().toString());
                }
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
            }
        }

        adjectives.put(adjective, adjectiveValue);
    }

    Object nounValue = null;
    if (operation.getNounValueType() != null) {
        Class nounValueType = operation.getNounValueType();
        if ((nounValueType.equals(DataHandler.class))
                || ((nounValueType.isArray() && nounValueType.getComponentType().equals(DataHandler.class)))) {
            Collection<DataHandler> dataHandlers;
            if (this.multipartRequestHandler != null) {
                dataHandlers = this.multipartRequestHandler.parseParts(request);
            } else {
                dataHandlers = new ArrayList<DataHandler>();
                dataHandlers.add(new DataHandler(
                        new RESTRequestDataSource(request, resource.getNounContext() + resource.getNoun())));
            }

            nounValue = dataHandlers;
            if (operation.getNounValueType().equals(DataHandler.class)) {
                nounValue = dataHandlers.iterator().next();
            } else if (mustConvertNounValueToArray(operation)) {
                Class type = operation.getNounValueType();
                if ((type.isArray() && type.getComponentType().equals(DataHandler.class))) {
                    nounValue = dataHandlers.toArray(new DataHandler[dataHandlers.size()]);
                }
            }
        } else {
            try {
                //if the operation has a noun value type, unmarshall it from the body....
                nounValue = handler.read(request);
            } catch (Exception e) {
                //if we can't unmarshal the noun value, continue if the noun value is optional.
                if (!operation.isNounValueOptional()) {
                    throw e;
                }
            }
        }
    }

    Object result = operation.invoke(properNounValue, contextParameterValues, adjectives, nounValue,
            this.endpoints.get(operation.getVerb()));

    //successful invocation, set up the response...
    if (result instanceof DataHandler) {
        response.setContentType(((DataHandler) result).getContentType());
        ((DataHandler) result).writeTo(response.getOutputStream());
    } else {
        response.setContentType(
                String.format("%s; charset=%s", operation.getContentType(), operation.getCharset()));
        handler.write(result, request, response);
    }
    return null;
}

From source file:org.jasig.cas.web.ServiceValidateController.java

@Override
protected final ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    final WebApplicationService service = this.argumentExtractor.extractService(request);
    final String serviceTicketId = service != null ? service.getArtifactId() : null;

    if (service == null || serviceTicketId == null) {
        logger.debug("Could not identify service and/or service ticket. Service: {}, Service ticket id: {}",
                service, serviceTicketId);
        return generateErrorView("INVALID_REQUEST", "INVALID_REQUEST", null);
    }/*from   www  . j  av a  2 s .  c o  m*/

    try {
        final Credential serviceCredential = getServiceCredentialsFromRequest(request);
        String proxyGrantingTicketId = null;

        if (serviceCredential != null) {
            try {
                proxyGrantingTicketId = this.centralAuthenticationService
                        .delegateTicketGrantingTicket(serviceTicketId, serviceCredential);
            } catch (final AuthenticationException e) {
                logger.info("Failed to authenticate service credential {}", serviceCredential);
            } catch (final TicketException e) {
                logger.error("Failed to create proxy granting ticket for {}", serviceCredential, e);
            }

            if (StringUtils.isEmpty(proxyGrantingTicketId)) {
                return generateErrorView("INVALID_PROXY_CALLBACK", "INVALID_PROXY_CALLBACK",
                        new Object[] { serviceCredential.getId() });
            }
        }

        final Assertion assertion = this.centralAuthenticationService.validateServiceTicket(serviceTicketId,
                service);

        final ValidationSpecification validationSpecification = this.getCommandClass();
        final ServletRequestDataBinder binder = new ServletRequestDataBinder(validationSpecification,
                "validationSpecification");
        initBinder(request, binder);
        binder.bind(request);

        if (!validationSpecification.isSatisfiedBy(assertion)) {
            logger.debug("Service ticket [{}] does not satisfy validation specification.", serviceTicketId);
            return generateErrorView("INVALID_TICKET", "INVALID_TICKET_SPEC", null);
        }

        String proxyIou = null;
        if (serviceCredential != null && proxyGrantingTicketId != null
                && this.proxyHandler.canHandle(serviceCredential)) {
            proxyIou = this.proxyHandler.handle(serviceCredential, proxyGrantingTicketId);
            if (StringUtils.isEmpty(proxyIou)) {
                return generateErrorView("INVALID_PROXY_CALLBACK", "INVALID_PROXY_CALLBACK",
                        new Object[] { serviceCredential.getId() });
            }
        }

        onSuccessfulValidation(serviceTicketId, assertion);
        logger.debug("Successfully validated service ticket {} for service [{}]", serviceTicketId,
                service.getId());
        return generateSuccessView(assertion, proxyIou);
    } catch (final TicketValidationException e) {
        return generateErrorView(e.getCode(), e.getCode(),
                new Object[] { serviceTicketId, e.getOriginalService().getId(), service.getId() });
    } catch (final TicketException te) {
        return generateErrorView(te.getCode(), te.getCode(), new Object[] { serviceTicketId });
    } catch (final UnauthorizedProxyingException e) {
        return generateErrorView(e.getMessage(), e.getMessage(), new Object[] { service.getId() });
    } catch (final UnauthorizedServiceException e) {
        return generateErrorView(e.getMessage(), e.getMessage(), null);
    }
}

From source file:org.nextframework.controller.MultiActionController.java

/**
 * Invokes the named method./*from  w  w  w . j a v  a 2s .c om*/
 * <p>
 * Uses a custom exception handler if possible; otherwise, throw an
 * unchecked exception; wrap a checked exception or Throwable.
 * @param useCommand 
 */
@SuppressWarnings("deprecation")
protected final ModelAndView invokeNamedMethod(Method method, WebRequestContext request, Object useCommand)
        throws Exception {
    //TODO TRATAMENTO DE LOOP ETERNO (REFERENCIA CIRCULAR)

    do {
        Input input = null;
        boolean fromErrors = false;
        try {
            List<Object> params = new ArrayList<Object>(2);
            boolean hasRequestParameter = method.getParameterTypes().length > 0
                    && method.getParameterTypes()[0].isAssignableFrom(WebRequestContext.class)
                    && !method.getParameterTypes()[0].equals(Object.class);
            if (hasRequestParameter) {
                params.add(request);
            }

            if (useCommand == null) {
                input = getAnnotation(method, Input.class);//modificado em 22/10/2010, esse cdigo ficava dentro do if.. e s funcionava caso existissem commands
                if ((hasRequestParameter && method.getParameterTypes().length == 2)
                        || (!hasRequestParameter && method.getParameterTypes().length == 1)) {
                    Class<?> commandClass = getCommandClass(method, hasRequestParameter ? 1 : 0);
                    CommandInfo commandInfo = getCommandInfo(method);

                    Object command;
                    ServletRequestDataBinder binder;

                    if (!fromErrors) {
                        command = getCommandObject(request, commandClass, commandInfo);
                        binder = bind(request, command, commandInfo.validate);
                    } else {
                        command = getCommandObject(request, commandClass, commandInfo);
                        //se veio de erros nao fazer o bind novamente
                        binder = new ServletRequestDataBinder(command, getCommandName(command));
                    }

                    params.add(command);

                    if (binder.getBindingResult().hasErrors()) {
                        String inputAction = null;

                        if (input != null) {
                            inputAction = input.value();
                        } else {
                            logger.warn("No @Input specified for method " + method.getDeclaringClass().getName()
                                    + "." + method.getName() + ". Bind errors.");
                            new BindException(binder.getBindingResult()).printStackTrace();
                            if (commandInfo.session) {
                                //should reset the command
                                command = instantiateNewSessionCommand(request, commandClass,
                                        getSessionCommandName(commandClass, commandInfo));
                                inputAction = method.getName();
                            }
                        }
                        if (inputAction != null) {
                            ((DefaultWebRequestContext) request).setLastAction(inputAction);
                            Method handlerMethod = this.methodNameResolver.getHandlerMethod(inputAction);
                            ((DefaultWebRequestContext) request)
                                    .setBindException(new BindException(binder.getBindingResult()));
                            if (!handlerMethod.getName().equals(method.getName())) {
                                //o input deve ter o mesmo command do mtodo que declarou o input .. ento deixaremos o mtodo de input.. fazer o handling como o mesmo command
                                ((DefaultWebRequestContext) request)
                                        .setBindException(new BindException(binder.getBindingResult()));
                                method = handlerMethod;
                            }
                        } else {
                            binder.close();
                        }
                    }
                }
            } else {
                params.add(useCommand);
            }
            Object result = method.invoke(this.delegate, params.toArray(new Object[params.size()]));
            return convertActionResultToModelAndView(method, result);
        } catch (NoSuchRequestHandlingMethodException e) {
            throw e;
        } catch (NextException e) {
            throw e;
        } catch (InvocationTargetException ex) {
            // the invoked method threw exception
            if (input == null) {
                OnErrors onErrors = getAnnotation(method, OnErrors.class);
                if (onErrors != null) {
                    fromErrors = true;
                    ((DefaultWebRequestContext) request).setLastAction(onErrors.value());
                    Method methodErrors = this.methodNameResolver.getHandlerMethod(onErrors.value());
                    request.addError(ex.getTargetException());
                    logger.error("Erro ao invocar mtodo " + method.getName() + " da classe "
                            + this.getClass().getName() + ". Redirecionando para onErrors: " + onErrors.value(),
                            ex.getTargetException());
                    method = methodErrors;
                    continue;
                } else {
                    // nao tem input e no tem onerrors.. deixar a exceo vazar para algum handler se for o caso
                }
            } else {
                //se tem input.. redirecionar para input
                boolean sameMethod = false;
                String inputName = input.value();

                Method handlerMethod = this.methodNameResolver.getHandlerMethod(inputName);
                sameMethod = handlerMethod.getName().equals(method.getName());

                //   se for o mesmo mtodo.. deixar a excecao vazar (se mandar para o mtodo denovo vai dar loop eterno porque a excecao vai ocorrer novamente
                if (!sameMethod) {
                    // se nao for o mesmo mtodo.. redirecionar
                    // poderiamos mandar um flag j que o mtodo a ser invocado tem o mesmo command .. nesse caso economizariamos o bind
                    // mas vamos deixar fazer o bind novamente porque j pode ter ocorrido algum processamento que alterou os valores do command 
                    method = handlerMethod;
                    request.addError(ex.getTargetException());
                    ((DefaultWebRequestContext) request).setLastAction(inputName);
                    logger.error(
                            "Erro ao invocar mtodo " + method.getName() + " da classe "
                                    + this.getClass().getName() + ". Redirecionando para input: " + inputName,
                            ex.getTargetException());
                    continue;
                }
            }
            return handleException(request, ex.getTargetException());
        } catch (IllegalArgumentException ex) {
            throw new NextException(
                    "No foi possvel invocar o mtodo. Se estiver utilizando o mtodo continueToAction verifique se o mtodo que pede o redirecionamento e o mtodo de destino possuem a mesma classe de command",
                    ex);
        } catch (Exception ex) {
            // The binding process threw an exception.
            return handleException(request, ex);
        }
    } while (true);
}

From source file:org.springframework.web.multipart.commons.CommonsMultipartResolverTests.java

private void doTestBinding(MockCommonsMultipartResolver resolver, MockHttpServletRequest originalRequest,
        MultipartHttpServletRequest request) throws UnsupportedEncodingException {

    MultipartTestBean1 mtb1 = new MultipartTestBean1();
    assertArrayEquals(null, mtb1.getField1());
    assertEquals(null, mtb1.getField2());
    ServletRequestDataBinder binder = new ServletRequestDataBinder(mtb1, "mybean");
    binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    binder.bind(request);/*  ww  w  .j  av a  2s .  c o  m*/
    List<MultipartFile> file1List = request.getFiles("field1");
    CommonsMultipartFile file1a = (CommonsMultipartFile) file1List.get(0);
    CommonsMultipartFile file1b = (CommonsMultipartFile) file1List.get(1);
    CommonsMultipartFile file2 = (CommonsMultipartFile) request.getFile("field2");
    assertEquals(file1a, mtb1.getField1()[0]);
    assertEquals(file1b, mtb1.getField1()[1]);
    assertEquals(new String(file2.getBytes()), new String(mtb1.getField2()));

    MultipartTestBean2 mtb2 = new MultipartTestBean2();
    assertArrayEquals(null, mtb2.getField1());
    assertEquals(null, mtb2.getField2());
    binder = new ServletRequestDataBinder(mtb2, "mybean");
    binder.registerCustomEditor(String.class, "field1", new StringMultipartFileEditor());
    binder.registerCustomEditor(String.class, "field2", new StringMultipartFileEditor("UTF-16"));
    binder.bind(request);
    assertEquals(new String(file1a.getBytes()), mtb2.getField1()[0]);
    assertEquals(new String(file1b.getBytes()), mtb2.getField1()[1]);
    assertEquals(new String(file2.getBytes(), "UTF-16"), mtb2.getField2());

    resolver.cleanupMultipart(request);
    assertTrue(((MockFileItem) file1a.getFileItem()).deleted);
    assertTrue(((MockFileItem) file1b.getFileItem()).deleted);
    assertTrue(((MockFileItem) file2.getFileItem()).deleted);

    resolver.setEmpty(true);
    request = resolver.resolveMultipart(originalRequest);
    binder.setBindEmptyMultipartFiles(false);
    String firstBound = mtb2.getField2();
    binder.bind(request);
    assertFalse(mtb2.getField2().isEmpty());
    assertEquals(firstBound, mtb2.getField2());

    request = resolver.resolveMultipart(originalRequest);
    binder.setBindEmptyMultipartFiles(true);
    binder.bind(request);
    assertTrue(mtb2.getField2().isEmpty());
}

From source file:org.springframework.web.servlet.mvc.generic.GenericFormController.java

protected ServletRequestDataBinder createBinder(HttpServletRequest request, T formObject) throws Exception {
    ServletRequestDataBinder binder = new ServletRequestDataBinder(formObject, getFormObjectName(request));
    initBinder(request, binder);//from  ww w.  j a  va 2  s  .  co  m
    return binder;
}

From source file:org.springframework.web.servlet.mvc.multiaction.MultiActionController.java

/**
 * Create a new binder instance for the given command and request.
 * <p>Called by {@code bind}. Can be overridden to plug in custom
 * ServletRequestDataBinder subclasses.//from  ww w . j a va  2 s  .  co  m
 * <p>The default implementation creates a standard ServletRequestDataBinder,
 * and invokes {@code initBinder}. Note that {@code initBinder}
 * will not be invoked if you override this method!
 * @param request current HTTP request
 * @param command the command to bind onto
 * @return the new binder instance
 * @throws Exception in case of invalid state or arguments
 * @see #bind
 * @see #initBinder
 */
protected ServletRequestDataBinder createBinder(HttpServletRequest request, Object command) throws Exception {
    ServletRequestDataBinder binder = new ServletRequestDataBinder(command, getCommandName(command));
    initBinder(request, binder);
    return binder;
}