@Test public void shouldFailIfLoginFormIsNotValid() { //given RedirectAttributesModelMap map = new RedirectAttributesModelMap(); MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "loginForm"); bindingResult.addError(new FieldError("test", "test", "test")); LoginForm loginForm = new LoginForm(); loginForm.setLoginFormUrl("url"); //when String path = controller.login(loginForm, bindingResult, map, new MockHttpServletRequest(), new MockHttpServletResponse()); //then assertEquals(bindingResult.getAllErrors(), map.getFlashAttributes().get("errors")); assertEquals("redirect:url", path); }
@Test public void shouldFailRequestIfCannotLogin() { //given RedirectAttributesModelMap map = new RedirectAttributesModelMap(); MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "loginForm"); LoginForm loginForm = new LoginForm(); when(securityProvider.validate(any(LoginForm.class), any(HttpServletRequest.class), any(HttpServletResponse.class))).thenReturn(false); //when controller.login(loginForm, bindingResult, map, new MockHttpServletRequest(), new MockHttpServletResponse()); //then assertTrue(map.getFlashAttributes().containsKey("errors")); List<ObjectError> errors = (List<ObjectError>) map.getFlashAttributes().get("errors"); assertEquals("login.failed", errors.get(0).getCode()); assertTrue(errors.size() == 1); }
@Test public void testHasBindingErrorsModelAndViewElement() { MockHttpServletRequest request = new MockHttpServletRequest(RequestMethod.GET.name(), "/"); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new LinkedHashMap<String, Object>()); // Set servlet attributes in request context holder... RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); // Set BindingResult BindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "form"); bindingResult.reject(null, "My Error"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX, bindingResult); ModelAndViewElement modelAndViewElement = new ModelAndViewElement(); modelAndViewElement.setContent(modelAndView); // Set variables Map<String, Object> variables = new LinkedHashMap<>(); variables.put("content", modelAndViewElement); // Build block List<RenderedElement> elements = new LinkedList<>(); statusMessageBlock.build(elements, new HashMap<>(), variables); assertTrue(!elements.isEmpty()); }
@Test public void testHasBindingErrorsModelAndView() { MockHttpServletRequest request = new MockHttpServletRequest(RequestMethod.GET.name(), "/"); request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext); request.setAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE, new LinkedHashMap<String, Object>()); // Set servlet attributes in request context holder... RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); // Set BindingResult BindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "form"); bindingResult.reject(null, "My Error"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX, bindingResult); // Set variables Map<String, Object> variables = new LinkedHashMap<>(); variables.put("content", modelAndView); // Build block List<RenderedElement> elements = new LinkedList<>(); statusMessageBlock.build(elements, new HashMap<>(), variables); assertTrue(!elements.isEmpty()); }
public String[] createRelationship(Integer personAId, Integer personBId, Integer relationshipTypeId, String startDateStr) throws Exception { PersonService ps = Context.getPersonService(); Person personA = ps.getPerson(personAId); Person personB = ps.getPerson(personBId); RelationshipType relType = Context.getPersonService().getRelationshipType(relationshipTypeId); Relationship rel = new Relationship(); rel.setPersonA(personA); rel.setPersonB(personB); rel.setRelationshipType(relType); if (StringUtils.isNotBlank(startDateStr)) { rel.setStartDate(Context.getDateFormat().parse(startDateStr)); } Map<String, String> map = new HashMap<String, String>(); MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName()); new RelationshipValidator().validate(rel, errors); String errmsgs[]; if (!errors.hasErrors()) { ps.saveRelationship(rel); errmsgs = null; return errmsgs; } errmsgs = errors.getGlobalError().getCodes(); return errmsgs; }
public boolean changeRelationshipDates(Integer relationshipId, String startDateStr, String endDateStr) throws Exception { Relationship r = Context.getPersonService().getRelationship(relationshipId); Date startDate = null; if (StringUtils.isNotBlank(startDateStr)) { startDate = Context.getDateFormat().parse(startDateStr); } Date endDate = null; if (StringUtils.isNotBlank(endDateStr)) { endDate = Context.getDateFormat().parse(endDateStr); } r.setStartDate(startDate); r.setEndDate(endDate); Map<String, String> map = new HashMap<String, String>(); MapBindingResult errors = new MapBindingResult(map, Relationship.class.getName()); new RelationshipValidator().validate(r, errors); if (errors.hasErrors()) { return false; } else { Context.getPersonService().saveRelationship(r); return true; } }
@Test public void testPKCS10Validator() throws Exception { String csrPemStr = this.getCsrIrregularOrderDN(); CsrRequestValidationConfigParams params = new CsrRequestValidationConfigParams("UK", "eScienceDev"); PKCS10Validator validator = new PKCS10Validator(params); assertTrue(validator.supports(csrPemStr.getClass())); Errors errors = new MapBindingResult(new HashMap<String, String>(), "csrPemStr"); validator.validate(csrPemStr, errors); assertTrue(errors.hasErrors() == false); validator.validate("invalid csr string", errors); assertTrue(errors.hasErrors()); //System.out.println(errors.getAllErrors().get(0)); }
@Test public void testConstructFromSpringErrors() { MessageCodesResolver mockMessageCodesResolver = mock(MessageCodesResolver.class); when(mockMessageCodesResolver.resolveMessageCodes("default.blank.message", "foo", "bar", null)).thenReturn(new String[] {"Property [bar] cannot be blank"}); when(mockMessageCodesResolver.resolveMessageCodes("default.blank.message", "foo", "baz", null)).thenReturn(new String[] {"Property [baz] cannot be blank"}); MapBindingResult errors = new MapBindingResult(new HashMap(), "foo"); errors.setMessageCodesResolver(mockMessageCodesResolver); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bar", "default.blank.message"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "baz", "default.blank.message"); JsonCError jsonc = new JsonCError(errors); assertThat(jsonc.getCode(), is("Property [bar] cannot be blank")); assertThat(jsonc.getMessage(), is("Field error in object 'foo' on field 'bar': rejected value [null]; codes [Property [bar] cannot be blank]; arguments []; default message [null]")); List<Map<String,Object>> errorList = jsonc.getErrors(); assertThat((String) errorList.get(0).get("code"), is("Property [bar] cannot be blank")); assertThat((String) errorList.get(0).get("message"), is("Field error in object 'foo' on field 'bar': rejected value [null]; codes [Property [bar] cannot be blank]; arguments []; default message [null]")); assertThat((String) errorList.get(1).get("code"), is("Property [baz] cannot be blank")); assertThat((String) errorList.get(1).get("message"), is("Field error in object 'foo' on field 'baz': rejected value [null]; codes [Property [baz] cannot be blank]; arguments []; default message [null]")); }
@Override protected void doValidate(Errors errors, Record target) { super.doValidate(errors, target); if (!errors.hasErrors()) { // Получаем существующие МЕТА-поля справочника Collection<MetaField> metaFields = metaFieldService.findAllByRelativeId(target.getDictionaryId(), null, true); // Проверяем значение первичного ключа doValidateMetaFields(errors, target, metaFields); // Если нет ошибок, то проверяем значение полей if (!errors.hasErrors()) { Errors fieldErrors = new MapBindingResult(target.getFields(), retrieveTargetClass().getSimpleName()); doValidateFields(fieldErrors, target, metaFields); errors.addAllErrors(fieldErrors); } } }
@Test public void succesfull_captcha_check() { mockRestServer.expect(requestTo(URL)) .andRespond(withSuccess("{\n" + " \"success\": true,\n" + " \"challenge_ts\": \"2016-01-01'T'12:12:1200\",\n" + " \"hostname\": \"some\",\n" + " \"error-codes\": []\n" + "}", MediaType.APPLICATION_JSON)); MapBindingResult bindingResult = bindingResult(); recaptchaVerifier.verify("response", bindingResult); assertThat(bindingResult.hasErrors(), is(false)); }
@Test public void failing_captcha_check() { mockRestServer.expect(requestTo(URL)) .andRespond(withSuccess("{\n" + " \"success\": false,\n" + " \"challenge_ts\": \"2016-01-01'T'12:12:1200\",\n" + " \"hostname\": \"some\",\n" + " \"error-codes\": [\"some\"]\n" + "}", MediaType.APPLICATION_JSON)); MapBindingResult bindingResult = bindingResult(); recaptchaVerifier.verify("response", bindingResult); assertThat(bindingResult.getAllErrors(), hasSize(1)); FieldError fieldError = (FieldError) bindingResult.getAllErrors().get(0); assertThat(fieldError.getObjectName(), is("followInitiative")); assertThat(fieldError.getField(), is("recaptcha")); assertThat(fieldError.getCode(), is("recaptcha.invalid")); assertThat(bindingResult.hasErrors(), is(true)); }
@Test public void testSubmitWithValidUser() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(TEST_USER); user.setPassword(TEST_PASSWORD); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", REDIRECT_VIEW.equals(viewName)); }
@Test public void testSubmitWithInvalidPassword() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(TEST_USER); user.setPassword(INVALID); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName)); }
@Test public void testSubmitWithNullPassword() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(TEST_USER); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName)); }
@Test public void testSubmitWithEmptyPassword() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(TEST_USER); user.setPassword(EMPTY); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName)); }
@Test public void testSubmitWithNullUserId() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(null); user.setPassword(TEST_PASSWORD); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName)); }
@Test public void testSubmitWithEmptyUserId() { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); MockHttpServletResponse response = new MockHttpServletResponse(); Model uiModel = new ExtendedModelMap(); MockUser user = (MockUser) getApplicationContext().getBean("user"); user.setUserId(EMPTY); user.setPassword(TEST_PASSWORD); MockHttpSession session = new MockHttpSession(); session.setAttribute(Constants.KME_MOCK_USER_KEY, user); request.setSession(session); BindingResult result = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName; try { viewName = getController().submit(request, response, uiModel, user, result); } catch (NullPointerException npe) { LOG.error(npe.getLocalizedMessage(), npe); viewName = null; } assertTrue("View name is incorrect.", LOGIN_VIEW.equals(viewName)); }
@Test public void testSubmit() { User user = new UserImpl(); user.setLoginName(USER[0]); getRequest().getSession().setAttribute(Constants.KME_USER_KEY, user); Backdoor backdoor = new Backdoor(); backdoor.setUserId(USER[0]); backdoor.setActualUser(null); getRequest().getSession().setAttribute(Constants.KME_BACKDOOR_USER_KEY, backdoor); Group group = new GroupImpl(); group.setName(BACKDOOR_GROUP); group.setId(new Long(87)); when(getController().getConfigParamService().findValueByName(any(String.class))).thenReturn(BACKDOOR_GROUP); when(getController().getGroupDao().getGroup(BACKDOOR_GROUP)).thenReturn(group); BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName = getController().submit(getRequest(), getResponse(), getUiModel(), backdoor, bindingResult); assertTrue("Failed to find proper view name.", VIEWS[1].equals(viewName)); User altUser = (User) request.getSession().getAttribute(Constants.KME_USER_KEY); assertTrue("Newly created user could not be retrieved from the session.", altUser != null); assertTrue("Group KME-BACKDOOR not found on user", altUser.isMember(BACKDOOR_GROUP)); }
@Test public void testSubmitWithEmptyBackdoorUser() { User user = new UserImpl(); user.setLoginName(USER[0]); getRequest().getSession().setAttribute(Constants.KME_USER_KEY, user); Backdoor backdoor = new Backdoor(); backdoor.setUserId(EMPTY); backdoor.setActualUser(user); getRequest().getSession().setAttribute(Constants.KME_BACKDOOR_USER_KEY, backdoor); BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName = getController().submit(getRequest(), getResponse(), getUiModel(), backdoor, bindingResult); assertTrue("Failed to find proper view name.", VIEWS[0].equals(viewName)); assertTrue("Binding result did not contain the expected error.", bindingResult.hasErrors() && bindingResult.hasFieldErrors("userId")); }
@Test public void testSubmitWithNullBackdoorUser() { User user = new UserImpl(); user.setLoginName(USER[0]); getRequest().getSession().setAttribute(Constants.KME_USER_KEY, user); Backdoor backdoor = new Backdoor(); backdoor.setUserId(null); backdoor.setActualUser(null); getRequest().getSession().setAttribute(Constants.KME_BACKDOOR_USER_KEY, backdoor); BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), new String()); String viewName = getController().submit(getRequest(), getResponse(), getUiModel(), backdoor, bindingResult); assertTrue("Failed to find proper view name.", VIEWS[0].equals(viewName)); assertTrue("Binding result did not contain the expected error.", bindingResult.hasErrors() && bindingResult.hasFieldErrors("userId")); }
@Test public void extractBindingResultErrors() throws Exception { BindingResult bindingResult = new MapBindingResult( Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new BindException(bindingResult); testBindingResult(bindingResult, ex); }
@Test public void extractMethodArgumentNotValidExceptionBindingResultErrors() throws Exception { BindingResult bindingResult = new MapBindingResult( Collections.singletonMap("a", "b"), "objectName"); bindingResult.addError(new ObjectError("c", "d")); Exception ex = new MethodArgumentNotValidException(null, bindingResult); testBindingResult(bindingResult, ex); }
private void createAlfrescoDestination() { AlfrescoDestinationModel destModel = new AlfrescoDestinationModel(); destModel.setAlfPswd("admin"); destModel.setAlfUser("admin"); destModel.setDestinationURL("http://alex.xenit.eu:33556/alfresco/soapapi"); destModel.setName("Jenkins apix 42"); destModel.setNbrThreads(1); //destModel.setContentStoreId(-1); Map<?, ?> map = new HashMap<>(); BindingResult errors = new MapBindingResult(map, "lala"); ctrl.createDestination(destModel, errors); }
@Test public void shouldLoginSuccessfullyAndRedirect() { //given LoginForm form = new LoginForm(); RedirectAttributesModelMap map = new RedirectAttributesModelMap(); MapBindingResult bindingResult = new MapBindingResult(new HashMap<String, Object>(), "loginForm"); doReturn(true).when(securityProvider).validate(eq(form), any(HttpServletRequest.class), any(HttpServletResponse.class)); //when String path = controller.login(form, bindingResult, map, new MockHttpServletRequest(), new MockHttpServletResponse()); //then assertEquals("redirect:path", path); }
/** * Request a full certificate revocation (requires either a HOME RA or a CAOP). * If successful, a new <tt>crr</tt> row is created with status APPROVED. * * @param revokeCertFormBean Revoke data * @param clientData Client/calling RA * @return */ @Transactional public ProcessRevokeResult fullRevokeCertificate( RevokeCertFormBean revokeCertFormBean, CertificateRow clientData) { Errors errors = new MapBindingResult(new HashMap<String, String>(), "revokeRequest"); long revoke_cert_key = revokeCertFormBean.getCert_key(); long ra_cert_key = clientData.getCert_key(); log.info("RA full revocation by: [" + ra_cert_key + "] for certificate: [" + revoke_cert_key + "]"); log.debug("Reason: [" + revokeCertFormBean.getReason() + "]"); CertificateRow revokeCert = this.certDao.findById(revoke_cert_key); if (!this.isCertRevokable(revokeCert)) { errors.reject("invalid.revocation.cert.notvalid", "Revocation Failed - Certificate is not VALID or has expired"); log.warn("RA revocation failed by: [" + ra_cert_key + "] for certificate: [" + revoke_cert_key + "] - cert is not valid or has expired"); return new ProcessRevokeResult(errors); } if (!this.canUserDoFullRevoke(revokeCert)) { errors.reject("invalid.revocation.permission.denied", "Revocation Failed - Only Home RAs or CA Operators can do a full revocation"); log.warn("RA revocation failed by: [" + ra_cert_key + "] for certificate: [" + revoke_cert_key + "] - Only Home RAs or CA Operators can do a full revocation"); return new ProcessRevokeResult(errors); } // revoke with status approved long crrId = this.crrService.revokeCertificate(revoke_cert_key, ra_cert_key, revokeCertFormBean.getReason(), CrrManagerService.CRR_STATUS.APPROVED); return new ProcessRevokeResult(crrId); }
/** * Construct an instance to signify <b>success</b>. * @param req_key * @param csrWrapper * @param pkcs8PrivateKey Optional, the PKCS#8 PEM string or null */ public ProcessCsrResult(final Long req_key, final PKCS10_RequestWrapper csrWrapper, final String pkcs8PrivateKey) { if(req_key == null){ throw new IllegalArgumentException("req_key is null"); } if(csrWrapper == null){ throw new IllegalArgumentException("csrWrapper is null"); } this.success = true; this.errors = new MapBindingResult(new HashMap<String, String>(), "csrWrapper"); this.csrWrapper = csrWrapper; this.pkcs8PrivateKey = pkcs8PrivateKey; this.req_key = req_key; }
@Test public void testErrorWithBadInput() throws Exception { HttpServletRequest request = new MockHttpServletRequest(); Map<?, ?> target = new HashMap<>(); //target.put() BindingResult bindingResult = new MapBindingResult(target, "policy"); bindingResult.addError(new FieldError("policy", "name", "required")); bindingResult.addError(new FieldError("policy", "policyXml", "required")); when(errorAttributes.getError(any())).thenReturn(new MethodArgumentNotValidException(mock(MethodParameter.class), bindingResult)); assertResponse(request, INTERNAL_SERVER_ERROR, "{name=required, policyXml=required}"); }
@Before public void setup() { bindingResult = new MapBindingResult(new HashMap<>(), "postForm"); principal = () -> "12345"; controller = new BlogAdminController(blogService, teamRepository, dateFactory); }
@Before public void setUp() throws Exception { bindingResult = new MapBindingResult(new HashMap<>(), "insertRecord"); }
/** * Construct an instance to signify a <b>success</b>. * @param crrId */ public ProcessRevokeResult(Long crrId) { this.success = true; this.errors = new MapBindingResult(new HashMap<String, String>(), "revokeRequest"); this.crrId = crrId; }