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

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

Introduction

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

Prototype

public void bind(ServletRequest request) 

Source Link

Document

Bind the parameters of the given request to this binder's target, also binding multipart files in case of a multipart request.

Usage

From source file:com.hmsinc.epicenter.webapp.data.DownloadService.java

/**
 * @param request/*from   w w  w. java  2  s  .com*/
 * @return
 */
private AnalysisParametersDTO bind(final HttpServletRequest request) {

    final AnalysisParametersDTO queryParams = new AnalysisParametersDTO();

    final ServletRequestDataBinder binder = new ServletRequestDataBinder(queryParams);
    binder.registerCustomEditor(DateTime.class, new DateTimePropertyEditor());
    binder.registerCustomEditor(Properties.class, new EncodedPropertiesPropertyEditor());
    binder.bind(request);

    Validate.notNull(queryParams, "No parameters were specified");

    return queryParams;
}

From source file:gallery.web.controller.pages.cms.PagesCmsDelegate.java

public ModelAndView doMultiUpdate(HttpServletRequest req, HttpServletResponse resp) {
    //logger.fine("do=multi update");
    String action = req.getParameter("action");
    if ("multiUpdate".equals(action)) {
        PagesCms command = new PagesCms();
        BindingResult res = null;/*from   w w w .  ja  va  2 s .co  m*/

        ServletRequestDataBinder binder = new ServletRequestDataBinder(command);
        binder.bind(req);
        res = binder.getBindingResult();
        if (res.hasErrors()) {
            common.CommonAttributes.addErrorMessage("form_errors", req);
            //logger.fine("hasErrors");
        } else {
            int rez = service.updateObjectArrayShortById(new String[] { "sort", "active", "last" },
                    command.getId(), command.getSort(), command.getActive(), command.getLast());
            if (rez > 0) {
                common.CommonAttributes.addHelpMessage("operation_succeed", req);
                //logger.fine("not hasErrors");
            } else {
                common.CommonAttributes.addErrorMessage("operation_fail", req);
                //logger.fine("hasErrors");
            }
        }
    }
    //after updating values shoving all pages(doView)
    return doView(req, resp);
}

From source file:com.baosight.buapx.web.BuapxServiceValidateController.java

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) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Could not process request; Service: %s, Service Ticket Id: %s", service,
                    serviceTicketId));/*from  ww w  . j a va2  s . c o  m*/
        }
        return generateErrorView("INVALID_REQUEST", "INVALID_REQUEST", null);
    }

    try {
        final Credentials serviceCredentials = getServiceCredentialsFromRequest(request);
        String proxyGrantingTicketId = null;

        // XXX should be able to validate AND THEN use
        if (serviceCredentials != null) {
            try {
                proxyGrantingTicketId = this.centralAuthenticationService
                        .delegateTicketGrantingTicket(serviceTicketId, serviceCredentials);
            } catch (final TicketException e) {
                logger.error("TicketException generating ticket for: " + serviceCredentials, e);
            }
        }

        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)) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "ServiceTicket [" + serviceTicketId + "] does not satisfy validation specification.");
            }
            return generateErrorView("INVALID_TICKET", "INVALID_TICKET_SPEC", null);
        }

        onSuccessfulValidation(serviceTicketId, assertion);

        final ModelAndView success = new ModelAndView(this.successView);
        success.addObject(MODEL_ASSERTION, assertion);

        // ?????
        String sysCode = parseSysCode(assertion);

        // for usename mapping.???
        String mappedUser = validatePermissiontoSystem(assertion, sysCode);
        if (mappedUser == null) {
            return generateErrorView("INVALID_TICKET", "INVALID_TICKET_SPEC", null);
        }
        success.addObject("mappedUser", mappedUser);
        if (sysCode != null) {
            // add extra attribute
            addExtraParam(success, assertion);
        }

        if (serviceCredentials != null && proxyGrantingTicketId != null) {
            final String proxyIou = this.proxyHandler.handle(serviceCredentials, proxyGrantingTicketId);
            success.addObject(MODEL_PROXY_GRANTING_TICKET_IOU, proxyIou);
        }

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Successfully validated service ticket: %s", serviceTicketId));
        }

        return success;
    } 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 UnauthorizedServiceException e) {
        return generateErrorView(e.getMessage(), e.getMessage(), null);
    }
}

From source file:com.gzeport.casserver.controller.GzeportServiceValidateController.java

/**
 * @:usermanger???????? /*ww  w .j a  v a 2 s  .  c  o m*/
 * @?: luyd luyuandeng@gzeport.com
 * @: 2012-5-18?02:22:56 
 * @: GzeportServiceValidateController.java
 */
@SuppressWarnings("unchecked")
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) {
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Could not process request; Service: %s, Service Ticket Id: %s", service,
                    serviceTicketId));
        }
        return generateErrorView("INVALID_REQUEST", "INVALID_REQUEST", null);
    }

    try {
        final Credentials serviceCredentials = getServiceCredentialsFromRequest(request);
        String proxyGrantingTicketId = null;

        // XXX should be able to validate AND THEN use
        if (serviceCredentials != null) {
            try {
                proxyGrantingTicketId = this.centralAuthenticationService
                        .delegateTicketGrantingTicket(serviceTicketId, serviceCredentials);
            } catch (final TicketException e) {
                logger.error("TicketException generating ticket for: " + serviceCredentials, e);
            }
        }

        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)) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "ServiceTicket [" + serviceTicketId + "] does not satisfy validation specification.");
            }
            return generateErrorView("INVALID_TICKET", "INVALID_TICKET_SPEC", null);
        }

        onSuccessfulValidation(serviceTicketId, assertion);

        Principal principal = assertion.getChainedAuthentications()
                .get(assertion.getChainedAuthentications().size() - 1).getPrincipal();
        User user = this.userManager.findUserByUserCode(principal.getId());
        List<FuncModel> list = this.userManager.getFuncModelsList(null, String.valueOf(user.getUserId()));
        //  String userInfo=user.getUserCode()+"#"+user.getUserId()+"#"+user.getUserPwd();
        //   logger.info("++++____+++++"+userInfo);

        Map userMap = new HashMap();
        userMap.put("userId", StringHelp.trimNull(user.getUserId() != null ? user.getUserId().toString() : ""));
        userMap.put("userPwd", StringHelp.trimNull(user.getUserPwd()));
        userMap.put("userCode", StringHelp.trimNull(user.getUserCode()));
        userMap.put("userName", StringHelp.trimNull(user.getUserName()));
        userMap.put("isUse", StringHelp.trimNull(user.getIsUse()));
        userMap.put("customsCode", StringHelp.trimNull(user.getCustomsCode()));
        userMap.put("customsName", StringHelp.trimNull(user.getCustomsName()));
        userMap.put("company",
                StringHelp.trimNull(user.getCompany() != null ? user.getCompany().getCompanyId() : ""));
        userMap.put("userLoginType", StringHelp.trimNull(user.getUserLoginType()));
        userMap.put("createCompany", StringHelp.trimNull(user.getCreateCompany()));
        //userMap.put("userRoles", StringHelp.trimNull(user.getUserRoles().toString()));
        userMap.put("userSex", StringHelp.trimNull(user.getUserSex()));
        userMap.put("businessType", StringHelp.trimNull(user.getBusinessType()));
        userMap.put("createUser", StringHelp.trimNull(user.getCreateUser()));
        userMap.put("createTime", StringHelp
                .trimNull(user.getCreateTime() != null ? simpleDateFormat.format(user.getCreateTime()) : null));
        userMap.put("workUnit", StringHelp.trimNull(user.getWorkUnit()));
        userMap.put("cardId", StringHelp.trimNull(user.getCardId()));
        userMap.put("cardType", StringHelp.trimNull(user.getCardType()));
        userMap.put("regRoleId", StringHelp.trimNull(user.getRegRoleId()));
        userMap.put("customsCodeExt", StringHelp.trimNull(user.getCustomsCodeExt()));
        userMap.put("userTel", StringHelp.trimNull(user.getUserTel()));
        userMap.put("userDpt", StringHelp.trimNull(user.getUserDpt()));
        userMap.put("userDuty", StringHelp.trimNull(user.getUserDuty()));
        userMap.put("birthday", StringHelp
                .trimNull(user.getBirthday() != null ? simpleDateFormat.format(user.getBirthday()) : null));
        userMap.put("EMail", StringHelp.trimNull(user.getEMail()));
        userMap.put("certificate", StringHelp.trimNull(user.getCertificate()));
        userMap.put("clientsDesc", StringHelp.trimNull(user.getClientsDesc()));
        userMap.put("isModifyPwd", StringHelp.trimNull(user.getIsModifyPwd()));
        userMap.put("lastLoginTime", StringHelp.trimNull(
                user.getLastLoginTime() != null ? simpleDateFormat.format(user.getLastLoginTime()) : null));
        userMap.put("attachmentid",
                StringHelp.trimNull(user.getAttachmentid() != null ? user.getAttachmentid().toString() : ""));
        userMap.put("modifyPwdTime", StringHelp.trimNull(
                user.getModifyPwdTime() != null ? simpleDateFormat.format(user.getModifyPwdTime()) : null));
        userMap.put("newClients", StringHelp.trimNull(user.getNewClients()));
        userMap.put("newRoles", StringHelp.trimNull(user.getNewRoles()));
        userMap.put("roleCounts", StringHelp.trimNull(String.valueOf(user.getRoleCounts())));
        userMap.put("rolesDesc", StringHelp.trimNull(user.getRolesDesc()));

        Map companyMap = new HashMap();
        Company company = user.getCompany();
        if (company != null) {
            companyMap.put("brokerType", StringHelp.trimNull(company.getBrokerType()));
            companyMap.put("coClass", StringHelp.trimNull(company.getCoClass()));
            companyMap.put("companyId", StringHelp.trimNull(company.getCompanyId()));
            companyMap.put("companyName", StringHelp.trimNull(company.getCompanyName()));
            companyMap.put("companyState", StringHelp.trimNull(company.getCompanyState()));
            companyMap.put("companyType",
                    StringHelp.trimNull(
                            company.getCompanyType() != null
                                    ? company.getCompanyType().getTypeId().toString() + "|"
                                            + company.getCompanyType().getTypeName()
                                    : ""));
            companyMap.put("customsCode", StringHelp.trimNull(company.getCustomsCode()));
            companyMap.put("customsName", StringHelp.trimNull(company.getCustomsName()));
            companyMap.put("english", StringHelp.trimNull(company.getEnglish()));
            companyMap.put("engName", StringHelp.trimNull(company.getEngName()));
            companyMap.put("eportCard", StringHelp.trimNull(company.getEportCard()));
            companyMap.put("orgCode", StringHelp.trimNull(company.getOrgCode()));

        }

        Map funSysModel = null;
        ArrayList modelList = new ArrayList();
        if (list != null && list.size() > 0) {
            for (FuncModel model : list) {
                funSysModel = new HashMap();
                funSysModel.put("css", StringHelp.trimNull(model.getCss()));
                //  funSysModel.put("disabled", StringHelp.trimNull(model.get));
                // System.out.println("--type--"+model.getFuncSysType());
                funSysModel.put("funcCode", StringHelp.trimNull(model.getFuncCode()));
                funSysModel.put("funcId", StringHelp.trimNull(model.getFuncId()));
                funSysModel.put("funcIslast", StringHelp.trimNull(model.getFuncIslast()));
                funSysModel.put("funcIsmenu", StringHelp.trimNull(model.getFuncIsmenu()));
                funSysModel.put("funcmodel", StringHelp
                        .trimNull(model.getFuncmodel() != null ? model.getFuncmodel().getFuncId() : ""));
                funSysModel.put("funcResume", StringHelp.trimNull(model.getFuncResume()));
                funSysModel.put("funcName", StringHelp.trimNull(model.getFuncName()));
                funSysModel.put("funcSysType", StringHelp.trimNull(model.getFuncSysType()));
                funSysModel.put("funcUrl", StringHelp.trimNull(model.getFuncUrl()));
                funSysModel.put("funcUseType", StringHelp.trimNull(model.getFuncUseType()));
                funSysModel.put("funcUseType0", StringHelp.trimNull(model.getFuncUseType0()));
                funSysModel.put("funcUseType1", StringHelp.trimNull(model.getFuncUseType1()));
                funSysModel.put("funcUseType2", StringHelp.trimNull(model.getFuncUseType2()));
                funSysModel.put("funcUseType34", StringHelp.trimNull(model.getFuncUseType34()));
                funSysModel.put("images", StringHelp.trimNull(model.getImages()));
                modelList.add(funSysModel);
            }
        }

        final ModelAndView success = new ModelAndView(this.successView);
        success.addObject(MODEL_ASSERTION, assertion);
        /*            
        logger.info("LOGIN_USER:::========"+userMap);
        logger.info("LOGIN_COMPANY:::========"+companyMap);
        logger.info("LOGIN_FUNMODELLIST:::========"+modelList);
        */
        success.addObject(LONIN_USER, userMap);
        success.addObject(USER_COMPANY, companyMap);
        success.addObject(USER_FUN_SYSMODEL, modelList);

        if (serviceCredentials != null && proxyGrantingTicketId != null) {
            final String proxyIou = this.proxyHandler.handle(serviceCredentials, proxyGrantingTicketId);
            success.addObject(MODEL_PROXY_GRANTING_TICKET_IOU, proxyIou);
        }

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Successfully validated service ticket: %s", serviceTicketId));
        }

        return success;
    } 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 UnauthorizedServiceException e) {
        return generateErrorView(e.getMessage(), e.getMessage(), null);
    }
}

From source file:org.zht.framework.web.bind.resolver.FormModelMethodArgumentResolver.java

/**
 * {@inheritDoc}/*from  w w w .  j  a  va  2s  .co m*/
 * <p>Downcast {@link org.springframework.web.bind.WebDataBinder} to {@link org.springframework.web.bind.ServletRequestDataBinder} before binding.
 *
 * @throws Exception
 * @see org.springframework.web.servlet.mvc.method.annotation.ServletRequestDataBinderFactory
 */

protected void bindRequestParameters(ModelAndViewContainer mavContainer, WebDataBinderFactory binderFactory,
        WebDataBinder binder, NativeWebRequest request, MethodParameter parameter) throws Exception {

    Map<String, Boolean> hasProcessedPrefixMap = new HashMap<String, Boolean>();

    Class<?> targetType = binder.getTarget().getClass();
    ServletRequest servletRequest = prepareServletRequest(binder.getTarget(), request, parameter);
    WebDataBinder simpleBinder = binderFactory.createBinder(request, null, null);

    if (Collection.class.isAssignableFrom(targetType)) {//bind collection or array

        Type type = parameter.getGenericParameterType();
        Class<?> componentType = Object.class;

        Collection target = (Collection) binder.getTarget();

        List targetList = new ArrayList(target);

        if (type instanceof ParameterizedType) {
            componentType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
        }

        if (parameter.getParameterType().isArray()) {
            componentType = parameter.getParameterType().getComponentType();
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) { //? array=1&array=2
                    for (Object value : paramValues.values()) {
                        targetList.add(simpleBinder.convertIfNecessary(value, componentType));
                    }
                } else { //? array[0]=1&array[1]=2
                    int index = Integer.valueOf(matcher.group(1));

                    if (targetList.size() <= index) {
                        growCollectionIfNecessary(targetList, index);
                    }
                    targetList.set(index, simpleBinder.convertIfNecessary(paramValues.values(), componentType));
                }
            } else { //? votes[1].title=votes[1].title&votes[0].title=votes[0].title&votes[0].id=0&votes[1].id=1
                Object component = null;
                //? ?????
                Matcher matcher = INDEX_PATTERN.matcher(prefixName);
                if (!matcher.matches()) {
                    throw new IllegalArgumentException("bind collection error, need integer index, key:" + key);
                }
                int index = Integer.valueOf(matcher.group(1));
                if (targetList.size() <= index) {
                    growCollectionIfNecessary(targetList, index);
                }
                Iterator iterator = targetList.iterator();
                for (int i = 0; i < index; i++) {
                    iterator.next();
                }
                component = iterator.next();

                if (component == null) {
                    component = BeanUtils.instantiate(componentType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);
                    validateIfApplicable(componentBinder, parameter);
                    if (componentBinder.getBindingResult().hasErrors()) {
                        if (isBindExceptionRequired(componentBinder, parameter)) {
                            throw new BindException(componentBinder.getBindingResult());
                        }
                    }
                    targetList.set(index, component);
                }
            }
            target.clear();
            target.addAll(targetList);
        }
    } else if (MapWapper.class.isAssignableFrom(targetType)) {

        Type type = parameter.getGenericParameterType();
        Class<?> keyType = Object.class;
        Class<?> valueType = Object.class;

        if (type instanceof ParameterizedType) {
            keyType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0];
            valueType = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[1];
        }

        MapWapper mapWapper = ((MapWapper) binder.getTarget());
        Map target = mapWapper.getInnerMap();
        if (target == null) {
            target = new HashMap();
            mapWapper.setInnerMap(target);
        }

        for (Object key : servletRequest.getParameterMap().keySet()) {
            String prefixName = getPrefixName((String) key);

            //?prefix ??
            if (hasProcessedPrefixMap.containsKey(prefixName)) {
                continue;
            } else {
                hasProcessedPrefixMap.put(prefixName, Boolean.TRUE);
            }

            Object keyValue = simpleBinder.convertIfNecessary(getMapKey(prefixName), keyType);

            if (isSimpleComponent(prefixName)) { //bind simple type
                Map<String, Object> paramValues = WebUtils.getParametersStartingWith(servletRequest,
                        prefixName);

                for (Object value : paramValues.values()) {
                    target.put(keyValue, simpleBinder.convertIfNecessary(value, valueType));
                }
            } else {

                Object component = target.get(keyValue);
                if (component == null) {
                    component = BeanUtils.instantiate(valueType);
                }

                WebDataBinder componentBinder = binderFactory.createBinder(request, component, null);
                component = componentBinder.getTarget();

                if (component != null) {
                    ServletRequestParameterPropertyValues pvs = new ServletRequestParameterPropertyValues(
                            servletRequest, prefixName, "");
                    componentBinder.bind(pvs);

                    validateComponent(componentBinder, parameter);

                    target.put(keyValue, component);
                }
            }
        }
    } else {//bind model
        ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
        servletBinder.bind(servletRequest);
    }
}

From source file:com.hihsoft.baseclass.web.controller.BaseController.java

/**
 * Request. Spring MVCBind?,??//w w  w  .j av a2s.  c o m
 * 
 * @return 
 * @see #preBind(HttpServletRequest,Object,ServletRequestDataBinder)
 */
protected BindingResult bindObject(final HttpServletRequest request, final Object command) throws Exception {
    Assert.notNull(command);

    // Binder
    final ServletRequestDataBinder binder = createBinder(request, command);
    // ?binder?,?binder?
    preBind(request, command, binder);

    // 
    binder.bind(request);

    // 
    final Validator[] validators = getValidators();
    if (validators != null) {
        for (final Validator validator : validators) {
            if (validator.supports(command.getClass())) {
                ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
            }
        }
    }
    return binder.getBindingResult();
}

From source file:org.openmrs.web.controller.ConceptFormControllerTest.java

/**
 * @see ConceptFormBackingObject#getConceptFromFormData()
 *//*  www. jav  a2 s.  co m*/
@Test
@Verifies(value = "should set concept on concept answers", method = "getConceptFromFormData()")
public void getConceptFromFormData_shouldSetConceptOnConceptAnswers() throws Exception {
    int conceptId = 21;

    Concept concept = conceptService.getConcept(conceptId);
    assertNotNull(concept);

    int initialCount = concept.getAnswers().size();

    ConceptFormController conceptFormController = (ConceptFormController) applicationContext
            .getBean("conceptForm");
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();

    mockRequest.setMethod("POST");
    mockRequest.setParameter("action", "Save Concept");
    mockRequest.setParameter("conceptId", "21");
    mockRequest.setParameter("namesByLocale[en].name", concept.getName().getName());
    mockRequest.setParameter("concept.datatype", "2");
    mockRequest.setParameter("concept.answers", "7 8 22 5089");

    ConceptFormBackingObject cb = conceptFormController.formBackingObject(mockRequest);

    // Bind the request parameters
    ServletRequestDataBinder srdb = new ServletRequestDataBinder(cb);
    conceptFormController.initBinder(mockRequest, srdb);
    srdb.bind(mockRequest);

    Concept parsedConcept = cb.getConceptFromFormData();

    assertEquals(initialCount + 1, parsedConcept.getAnswers().size());
    for (ConceptAnswer ca : parsedConcept.getAnswers()) {
        assertNotNull(ca.getConcept());
    }
}

From source file:net.unicon.cas.mfa.web.MultiFactorServiceValidateController.java

/**
 * <p>Handle the request. Specially, abides by the default behavior specified in the {@link org.jasig.cas.web.ServiceValidateController}
 * and then, invokes the {@link #getCommandClass()} method to delegate the task of spec validation.
 * @param request request object/*  ww  w. j a  v a  2 s.c  o m*/
 * @param response response object
 * @return A {@link ModelAndView} object pointing to either {@link #setSuccessView(String)} or {@link #setFailureView(String)}
 * @throws Exception In case the authentication method cannot be retrieved by the binder from the incoming request.
 */
@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;
    final String authnMethod = getAuthenticationMethodFromRequest(request);

    if (service == null || serviceTicketId == null) {
        logger.debug(String.format("Could not process request; Service: %s, Service Ticket Id: %s", service,
                serviceTicketId));
        return generateErrorView("INVALID_REQUEST", "INVALID_REQUEST", authnMethod, null);
    }

    try {
        final Credentials serviceCredentials = getServiceCredentialsFromRequest(request);
        String proxyGrantingTicketId = null;

        if (serviceCredentials != null) {
            try {
                proxyGrantingTicketId = this.centralAuthenticationService
                        .delegateTicketGrantingTicket(serviceTicketId, serviceCredentials);
            } catch (final TicketException e) {
                logger.error("TicketException generating ticket for: " + serviceCredentials, e);
            }
        }

        final Assertion assertion = this.centralAuthenticationService.validateServiceTicket(serviceTicketId,
                service);
        final AbstractMultiFactorAuthenticationProtocolValidationSpecification validationSpecification = this
                .getCommandClass();
        final ServletRequestDataBinder binder = new ServletRequestDataBinder(validationSpecification,
                "validationSpecification");
        initBinder(request, binder);
        binder.bind(request);

        /**
         * The binder does not support field aliases. This means that the request parameter names
         * must exactly match the validation spec fields, or the match fails. Since the validation request
         * per the modified protocol will use 'authn_method', we could either create a matching field
         * inside the validation object, create a custom data binder object that does the conversion,
         * or simply bind the parameter manually.
         *
         * This implementation opts for the latter choice.
         */
        validationSpecification.setAuthenticationMethod(authnMethod);

        try {
            if (!validationSpecification.isSatisfiedBy(assertion)) {
                logger.debug(
                        "ServiceTicket [" + serviceTicketId + "] does not satisfy validation specification.");
                return generateErrorView("INVALID_TICKET", "INVALID_TICKET_SPEC", authnMethod, null);
            }
        } catch (final UnrecognizedMultiFactorAuthenticationMethodException e) {
            logger.debug(e.getMessage(), e);
            return generateErrorView(e.getCode(), e.getMessage(), authnMethod,
                    new Object[] { e.getAuthenticationMethod() });
        } catch (final UnacceptableMultiFactorAuthenticationMethodException e) {
            logger.debug(e.getMessage(), e);
            return generateErrorView(e.getCode(), e.getMessage(), authnMethod,
                    new Object[] { serviceTicketId, e.getAuthenticationMethod() });
        }

        onSuccessfulValidation(serviceTicketId, assertion);

        final ModelAndView success = new ModelAndView(this.successView);
        success.addObject(MODEL_ASSERTION, assertion);

        if (serviceCredentials != null && proxyGrantingTicketId != null) {
            final String proxyIou = this.proxyHandler.handle(serviceCredentials, proxyGrantingTicketId);
            success.addObject(MODEL_PROXY_GRANTING_TICKET_IOU, proxyIou);
        }

        final String authnMethods = MultiFactorUtils.getFulfilledAuthenticationMethodsAsString(assertion);
        if (StringUtils.isNotBlank(authnMethods)) {
            success.addObject(MODEL_AUTHN_METHOD, authnMethods);
        }
        logger.debug(String.format("Successfully validated service ticket: %s", serviceTicketId));

        return success;
    } catch (final TicketValidationException e) {
        return generateErrorView(e.getCode(), e.getCode(), authnMethod,
                new Object[] { serviceTicketId, e.getOriginalService().getId(), service.getId() });
    } catch (final TicketException te) {
        return generateErrorView(te.getCode(), te.getCode(), authnMethod, new Object[] { serviceTicketId });
    } catch (final UnauthorizedServiceException e) {
        return generateErrorView(e.getMessage(), e.getMessage(), authnMethod, null);
    }
}