Example usage for org.springframework.validation BindingResult getFieldError

List of usage examples for org.springframework.validation BindingResult getFieldError

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getFieldError.

Prototype

@Nullable
FieldError getFieldError(String field);

Source Link

Document

Get the first error associated with the given field, if any.

Usage

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductsController.java

@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody//  ww  w .j av  a 2  s. c  o  m
public String editProductLogo(@ModelAttribute("productLogoForm") ProductLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### edit product logo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                new Object[] { fileSize }, request.getLocale()));
        return error.toString();
    }

    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        Product product = form.getProduct();
        ProductLogoFormValidator validator = new ProductLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            setPage(map, Page.PRODUCTS);
            JsonObject error = new JsonObject();
            error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                    null, request.getLocale()));
            return error.toString();
        } else {
            try {
                product = productService.editProductLogo(product, form.getLogo());
            } catch (FileUploadException e) {
                logger.debug("###IO Exception in writing custom image file", e);
                result.rejectValue("logo", "error.uploading.file");
                JsonObject error = new JsonObject();
                error.addProperty("errormessage", messageSource
                        .getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
                return error.toString();
            }
        }
        String response = null;
        try {
            response = JSONUtils.toJSONString(product);
        } catch (JsonGenerationException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (JsonMappingException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (IOException e) {
            logger.debug("###IO Exception in writing custom image file");
        }
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        setPage(map, Page.PRODUCTS);
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        return error.toString();
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractChannelController.java

@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody/*from  ww  w  .  jav a 2 s .  c o m*/
public String editChannelLogo(@ModelAttribute("channelLogoForm") ChannelLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### editChannelLogo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                new Object[] { fileSize }, request.getLocale()));
        return error.toString();
    }
    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        Channel channel = channelService.getChannelById(form.getChannel().getId().toString());
        ChannelLogoFormValidator validator = new ChannelLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            JsonObject error = new JsonObject();
            setPage(map, Page.CHANNELS);
            error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                    null, request.getLocale()));
            return error.toString();
        } else {
            String channelsDir = "channels";
            File file = new File(FilenameUtils.concat(rootImageDir, channelsDir));
            if (!file.exists()) {
                file.mkdir();
            }
            String channelsAbsoluteDir = FilenameUtils.concat(rootImageDir, channelsDir);
            String relativeImageDir = FilenameUtils.concat(channelsDir, channel.getId().toString());
            File file1 = new File(FilenameUtils.concat(channelsAbsoluteDir, channel.getId().toString()));
            if (!file1.exists()) {
                file1.mkdir();
            }

            MultipartFile logoFile = form.getLogo();
            try {
                if (!logoFile.getOriginalFilename().trim().equals("")) {
                    String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir,
                            logoFile);
                    channel.setImagePath(logoFileRelativePath);
                }
                channelService.updateChannel(channel);
            } catch (IOException e) {
                logger.debug("###IO Exception in writing custom image file");
            }
        }
        String response = null;
        try {
            response = JSONUtils
                    .toJSONString(channelService.getChannelById(form.getChannel().getId().toString()));
        } catch (JsonGenerationException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (JsonMappingException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (IOException e) {
            logger.debug("###IO Exception in writing custom image file");
        }
        logger.debug("### editChannelLogo method ending (Success)...(POST)");
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        setPage(map, Page.CHANNELS);
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        logger.debug("### editChannelLogo method ending (No Image Logo Dir Defined)...(POST)");
        return error.toString();
    }
}

From source file:fragment.web.RegistrationControllerTest.java

@Test
public void testRegisterNotAcceptedTerms() throws Exception {
    MockHttpServletRequest mockRequest = getRequestTemplate(HttpMethod.GET, "/portal/register");
    UserRegistration registration = new UserRegistration();
    registration.setCountryList(countryService.getCountries(null, null, null, null, null, null, null));
    AccountType disposition = accountTypeDAO.getOnDemandPostPaidAccountType();
    BindingResult result = setupRegistration(disposition, registration);
    beforeRegisterCall(mockRequest, registration);
    String view = controller.register(registration, result, "abc", "abc", map, null, status, mockRequest);
    Assert.assertEquals("register.moreuserinfo", view);
    Assert.assertFalse(status.isComplete());
    Assert.assertTrue(result.hasFieldErrors());
    Assert.assertTrue(result.getFieldErrorCount() == 1);
    Assert.assertEquals("AssertTrue", result.getFieldError("acceptedTerms").getCode());
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractProductBundlesController.java

/**
 * This method is used to edit the Product Bundle logo
 * /*from w  w w .  j av  a2 s.  c o m*/
 * @param form
 * @param result
 * @param request
 * @param map
 * @return
 */
@RequestMapping(value = ("/editlogo"), method = RequestMethod.POST)
@ResponseBody
public String editBundleLogo(@ModelAttribute("bundleLogoForm") ProductBundleLogoForm form, BindingResult result,
        HttpServletRequest request, ModelMap map) {
    logger.debug("### editBundleLogo method starting...(POST)");
    String fileSize = checkFileUploadMaxSizeException(request);
    if (fileSize != null) {
        result.rejectValue("logo", "error.image.max.upload.size.exceeded");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage", messageSource.getMessage(result.getFieldError("logo").getCode(),
                new Object[] { fileSize }, request.getLocale()));
        return error.toString();
    }

    String rootImageDir = config.getValue(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    if (rootImageDir != null && !rootImageDir.trim().equals("")) {
        ProductBundle bundle = form.getBundle();
        ProductBundleLogoFormValidator validator = new ProductBundleLogoFormValidator();
        validator.validate(form, result);
        if (result.hasErrors()) {
            return messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale());
        } else {
            String bundlesDir = "productbundles";
            File file = new File(FilenameUtils.concat(rootImageDir, bundlesDir));
            if (!file.exists()) {
                file.mkdir();
            }
            String bundlesAbsoluteDir = FilenameUtils.concat(rootImageDir, bundlesDir);
            String relativeImageDir = FilenameUtils.concat(bundlesDir, bundle.getId().toString());
            File file1 = new File(FilenameUtils.concat(bundlesAbsoluteDir, bundle.getId().toString()));
            if (!file1.exists()) {
                file1.mkdir();
            }

            MultipartFile logoFile = form.getLogo();
            try {
                if (!logoFile.getOriginalFilename().trim().equals("")) {
                    String logoFileRelativePath = writeMultiPartFileToLocalFile(rootImageDir, relativeImageDir,
                            logoFile);
                    bundle.setImagePath(logoFileRelativePath);
                }
                bundle = productBundleService.updateProductBundle(bundle, false);
            } catch (IOException e) {
                logger.debug("###IO Exception in writing custom image file");
                result.rejectValue("logo", "error.uploading.file");
                JsonObject error = new JsonObject();
                error.addProperty("errormessage", messageSource
                        .getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
                return error.toString();
            }
        }
        String response = null;
        try {
            response = JSONUtils.toJSONString(bundle);
        } catch (JsonGenerationException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (JsonMappingException e) {
            logger.debug("###IO Exception in writing custom image file");
        } catch (IOException e) {
            logger.debug("###IO Exception in writing custom image file");
        }
        return response;
    } else {
        result.rejectValue("logo", "error.custom.image.upload.dir");
        JsonObject error = new JsonObject();
        error.addProperty("errormessage",
                messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale()));
        return error.toString();
    }
}

From source file:fragment.web.AbstractConnectorControllerTest.java

@Test
public void testUploadServiceInstanceLogoInvalidFile() throws Exception {

    Configuration configuration = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    configuration.setValue("src\\test\\resources");
    configurationService.update(configuration);
    ServiceInstance serviceInstance = serviceInstanceDao.find(1L);
    Assert.assertEquals(null, serviceInstance.getImagePath());
    MultipartFile logo = new MockMultipartFile("ServiceInstanceLogo.jpeg", "ServiceInstanceLogo.jpe", "byte",
            "ServiceInstance".getBytes());
    ServiceInstanceLogoForm form = new ServiceInstanceLogoForm(serviceInstance);
    form.setLogo(logo);//  w w w . ja v a2s .  com
    BindingResult result = validate(form);
    HttpServletRequest request = new MockHttpServletRequest();
    map = new ModelMap();
    String resultString = controller.uploadServiceInstanceLogo(form, result, request, map);
    Assert.assertNotNull(resultString);
    String Error = messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale());
    Assert.assertEquals(Error, resultString);
    serviceInstance = serviceInstanceDao.find(1L);
    Assert.assertEquals(null, serviceInstance.getImagePath());
}

From source file:fragment.web.AbstractConnectorControllerTest.java

@Test
public void testUploadServiceInstanceLogoNullDirectoryPath() throws Exception {

    Configuration configuration = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_images_uploadPath);
    configuration.setValue(null);/*from w w w.  j a v a  2s . com*/
    configurationService.update(configuration);

    ServiceInstance serviceInstance = serviceInstanceDao.find(1L);
    Assert.assertEquals(null, serviceInstance.getImagePath());
    MultipartFile logo = new MockMultipartFile("ServiceInstanceLogo.jpeg", "ServiceInstanceLogo.jpeg", "byte",
            "ServiceInstance".getBytes());
    ServiceInstanceLogoForm form = new ServiceInstanceLogoForm(serviceInstance);
    form.setLogo(logo);
    BindingResult result = validate(form);
    HttpServletRequest request = new MockHttpServletRequest();
    map = new ModelMap();
    String resultString = controller.uploadServiceInstanceLogo(form, result, request, map);
    Assert.assertNotNull(resultString);
    String Error = messageSource.getMessage(result.getFieldError("logo").getCode(), null, request.getLocale());
    Assert.assertEquals(Error, resultString);
    serviceInstance = serviceInstanceDao.find(1L);
    Assert.assertEquals(null, serviceInstance.getImagePath());
}

From source file:uk.ac.ebi.metabolights.controller.UserAccountController.java

/**
 * Handles creation of a new user account.<br>
 * Verify form input, check for clashes in database, store the
 * new account (status 'NEW') and let the user verify the request.
 *
 * @param metabolightsUser user details//  w ww .j  a v a  2 s.  c  o m
 * @param result Binding result
 * @param model
 * @return where to navigate next
 */
@RequestMapping(value = "/createNewAccount", method = RequestMethod.POST)
public ModelAndView createNewAccount(@Valid MetabolightsUser metabolightsUser, BindingResult result,
        Model model, HttpServletRequest request) {

    // The isatab schema works with a USERNAME. For Metabolights, we set the email address to be the user name,
    // it's easier for people to remember that
    metabolightsUser.setUserName(metabolightsUser.getEmail());

    boolean duplicateEmailAddress = false;

    if (TextUtils.textHasContent(metabolightsUser.getEmail()) && result.getFieldError("email") == null
            && emailExists(metabolightsUser.getEmail())) {
        duplicateEmailAddress = true;
    }

    if (result.hasErrors() || duplicateEmailAddress) {

        //ModelAndView mav = new ModelAndView("createAccount");
        ModelAndView mav = AppContext.getMAVFactory().getFrontierMav("createAccount");
        mav.addObject(metabolightsUser);
        if (duplicateEmailAddress) {
            mav.addObject("duplicateEmailAddress",
                    PropertyLookup.getMessage("Duplicate.metabolightsUser.email"));
        }
        return mav;
    }

    Long newUserId = null;

    try {
        //Store the user information in the database, status NEW means still inactive (to be authorized).
        metabolightsUser.setStatus(MetabolightsUser.UserStatus.NEW); // make account non usable yet
        metabolightsUser.setDbPassword(IsaTabAuthenticationProvider.encode(metabolightsUser.getDbPassword()));
        metabolightsUser.setApiToken(UUID.randomUUID().toString());
        newUserId = userService.insert(metabolightsUser);

        //Send user a verification email
        String uniqueURLParameter = numericSequence(metabolightsUser.getDbPassword());
        String confirmationURL = confirmNewAccountUrl + "?usr="
                + URLEncoder.encode(metabolightsUser.getUserName(), "UTF-8") + "&key=" + uniqueURLParameter;
        emailService.sendConfirmNewAccountRequest(metabolightsUser.getEmail(), confirmationURL);

    } catch (Exception ex) {
        ex.printStackTrace();
        //On exception, user gets deleted again
        if (newUserId != null)
            userService.delete(metabolightsUser);
        throw new RuntimeException(ex);
    }

    //Let the user know what will happen next
    //String emailShort=metabolightsUser.getEmail().substring(0,metabolightsUser.getEmail().indexOf('@'));

    HttpSession httpSession = request.getSession();
    httpSession.setAttribute("user", metabolightsUser);
    httpSession.setAttribute("country",
            metabolightsUser.getListOfAllCountries().get(metabolightsUser.getAddress()));

    return new ModelAndView("redirect:accountRequested");

    //return new ModelAndView("redirect:accountRequested="+emailShort);

}