Exemplo n.º 1
0
  @CacheEvict(value = "users", allEntries = true)
  @Transactional(propagation = Propagation.NOT_SUPPORTED)
  public List<User> bulkDeleteUser(UserBulkDeleteRequest bulkDeleteForm, BindingResult result) {
    List<User> users = new ArrayList<>();
    for (long id : bulkDeleteForm.getIds()) {
      final UserDeleteRequest deleteRequest = new UserDeleteRequest.Builder().id(id).build();

      final BeanPropertyBindingResult r = new BeanPropertyBindingResult(deleteRequest, "request");
      r.setMessageCodesResolver(messageCodesResolver);

      TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
      transactionTemplate.setPropagationBehavior(TransactionTemplate.PROPAGATION_REQUIRES_NEW);
      User user = null;
      try {
        user =
            transactionTemplate.execute(
                new TransactionCallback<User>() {
                  public User doInTransaction(TransactionStatus status) {
                    try {
                      return deleteUser(deleteRequest, r);
                    } catch (BindException e) {
                      throw new RuntimeException(e);
                    }
                  }
                });
        users.add(user);
      } catch (Exception e) {
        logger.debug("Errors: {}", r);
        result.addAllErrors(r);
      }
    }
    return users;
  }
 @Test
 public void testValidate_noContext() {
   BeanPropertyBindingResult errors =
       new BeanPropertyBindingResult(httpConnector, "httpConnector");
   httpConnector.validate(httpConnector, errors);
   assertEquals(1, errors.getFieldErrorCount());
   assertEquals("service.connector.port.required", errors.getFieldError("port").getCode());
 }
  @Test
  public void testValidTransaction() {
    Transaction trx = new Transaction(1L, 10D, "test", null);
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(trx, "transaction");
    ValidationUtils.invokeValidator(validator, trx, result);

    assertThat(result.hasErrors(), equalTo(false));
  }
  @Test
  public void testTransactionIdInvalid() {
    Transaction trx = new Transaction(null, 10D, "test", null);

    BeanPropertyBindingResult result = new BeanPropertyBindingResult(trx, "transaction");
    ValidationUtils.invokeValidator(validator, trx, result);

    assertThat(result.hasErrors(), equalTo(true));
    assertThat(result.getErrorCount(), equalTo(1));
  }
  public void testWithMultiValueWithFormatter() throws Exception {
    this.tag.setPath("stringArray");
    this.tag.setItems(new Object[] {"   foo", "   bar", "   baz"});
    BeanPropertyBindingResult bindingResult =
        new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    FormattingConversionService cs = new FormattingConversionService();
    cs.addFormatterForFieldType(
        String.class,
        new Formatter<String>() {
          public String print(String object, Locale locale) {
            return object;
          }

          public String parse(String text, Locale locale) throws ParseException {
            return text.trim();
          }
        });
    bindingResult.initConversion(cs);
    getPageContext()
        .getRequest()
        .setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getOutput();

    // wrap the output so it is valid XML
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element spanElement1 = (Element) document.getRootElement().elements().get(0);
    Element checkboxElement1 = (Element) spanElement1.elements().get(0);
    assertEquals("input", checkboxElement1.getName());
    assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
    assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
    assertEquals("checked", checkboxElement1.attribute("checked").getValue());
    assertEquals("   foo", checkboxElement1.attribute("value").getValue());
    Element spanElement2 = (Element) document.getRootElement().elements().get(1);
    Element checkboxElement2 = (Element) spanElement2.elements().get(0);
    assertEquals("input", checkboxElement2.getName());
    assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
    assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
    assertEquals("checked", checkboxElement2.attribute("checked").getValue());
    assertEquals("   bar", checkboxElement2.attribute("value").getValue());
    Element spanElement3 = (Element) document.getRootElement().elements().get(2);
    Element checkboxElement3 = (Element) spanElement3.elements().get(0);
    assertEquals("input", checkboxElement3.getName());
    assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
    assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
    assertNull("not checked", checkboxElement3.attribute("checked"));
    assertEquals("   baz", checkboxElement3.attribute("value").getValue());
  }
Exemplo n.º 6
0
  public void testMultiBind() throws Exception {
    BeanPropertyBindingResult result = new BeanPropertyBindingResult(new TestBean(), "testBean");
    result
        .getPropertyAccessor()
        .registerCustomEditor(TestBean.class, "friends", new FriendEditor());
    exposeBindingResult(result);

    BindStatus bindStatus = new BindStatus(getRequestContext(), "testBean.friends", false);

    getPageContext().setAttribute(SelectTag.LIST_VALUE_PAGE_ATTRIBUTE, bindStatus);
    this.tag.setValue(new TestBean("foo"));
    this.tag.doStartTag();
    this.tag.doEndTag();

    assertEquals("<option value=\"foo\">foo</option>", getOutput());
  }
Exemplo n.º 7
0
  public void testWithCustomBinder() throws Exception {
    this.tag.setPath("myFloat");

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
    errors.getPropertyAccessor().registerCustomEditor(Float.class, new SimpleFloatEditor());
    exposeBindingResult(errors);

    assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());

    String output = getOutput();
    assertTagOpened(output);
    assertTagClosed(output);

    assertContainsAttribute(output, "type", getType());
    assertValueAttribute(output, "12.34f");
  }
  public void testWithMultiValueWithEditor() throws Exception {
    this.tag.setPath("stringArray");
    this.tag.setItems(new Object[] {"   foo", "   bar", "   baz"});
    BeanPropertyBindingResult bindingResult =
        new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    MyStringTrimmerEditor editor = new MyStringTrimmerEditor();
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, editor);
    getPageContext()
        .getRequest()
        .setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);
    assertEquals(3, editor.allProcessedValues.size());

    String output = getOutput();

    // wrap the output so it is valid XML
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element spanElement1 = (Element) document.getRootElement().elements().get(0);
    Element checkboxElement1 = (Element) spanElement1.elements().get(0);
    assertEquals("input", checkboxElement1.getName());
    assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
    assertEquals("stringArray", checkboxElement1.attribute("name").getValue());
    assertEquals("checked", checkboxElement1.attribute("checked").getValue());
    assertEquals("   foo", checkboxElement1.attribute("value").getValue());
    Element spanElement2 = (Element) document.getRootElement().elements().get(1);
    Element checkboxElement2 = (Element) spanElement2.elements().get(0);
    assertEquals("input", checkboxElement2.getName());
    assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
    assertEquals("stringArray", checkboxElement2.attribute("name").getValue());
    assertEquals("checked", checkboxElement2.attribute("checked").getValue());
    assertEquals("   bar", checkboxElement2.attribute("value").getValue());
    Element spanElement3 = (Element) document.getRootElement().elements().get(2);
    Element checkboxElement3 = (Element) spanElement3.elements().get(0);
    assertEquals("input", checkboxElement3.getName());
    assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
    assertEquals("stringArray", checkboxElement3.attribute("name").getValue());
    assertNull("not checked", checkboxElement3.attribute("checked"));
    assertEquals("   baz", checkboxElement3.attribute("value").getValue());
  }
Exemplo n.º 9
0
  public void testWithErrors() throws Exception {
    this.tag.setPath("name");
    this.tag.setCssClass("good");
    this.tag.setCssErrorClass("bad");

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(this.rob, COMMAND_NAME);
    errors.rejectValue("name", "some.code", "Default Message");
    errors.rejectValue("name", "too.short", "Too Short");
    exposeBindingResult(errors);

    assertEquals(Tag.SKIP_BODY, this.tag.doStartTag());

    String output = getOutput();
    assertTagOpened(output);
    assertTagClosed(output);

    assertContainsAttribute(output, "type", getType());
    assertValueAttribute(output, "Rob");
    assertContainsAttribute(output, "class", "bad");
  }
  private boolean doValidate(PersistentEntity entity, Object o) {
    Validator v = datastore.getMappingContext().getEntityValidator(entity);
    if (v == null) {
      return true;
    }

    final Object skipValidation =
        datastore.getCurrentSession().getAttribute(o, SKIP_VALIDATION_ATTRIBUTE);
    if ((skipValidation instanceof Boolean) && (Boolean) skipValidation) {
      return true;
    }

    BeanPropertyBindingResult result = new BeanPropertyBindingResult(o, o.getClass().getName());
    v.validate(o, result);
    if (result.hasErrors()) {
      onErrors(o, result);
      return false;
    }

    return true;
  }
Exemplo n.º 11
0
  public void testWithCollectionAndCustomEditor() throws Exception {
    PropertyEditor propertyEditor = new SimpleFloatEditor();

    TestBean target = new TestBean();
    target.setMyFloat(new Float("12.34"));

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(target, COMMAND_NAME);
    errors.getPropertyAccessor().registerCustomEditor(Float.class, propertyEditor);
    exposeBindingResult(errors);

    getPageContext()
        .setAttribute(
            SelectTag.LIST_VALUE_PAGE_ATTRIBUTE,
            new BindStatus(getRequestContext(), "testBean.myFloat", false));

    this.tag.setItems("${floats}");
    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);
    String output = getOutput();
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element rootElement = document.getRootElement();

    List children = rootElement.elements();
    assertEquals("Incorrect number of children", 6, children.size());

    Element element = (Element) rootElement.selectSingleNode("option[text() = '12.34f']");
    assertNotNull("Option node should not be null", element);
    assertEquals("12.34 node not selected", "selected", element.attribute("selected").getValue());
    assertNull("No id rendered", element.attribute("id"));

    element = (Element) rootElement.selectSingleNode("option[text() = '12.35f']");
    assertNotNull("Option node should not be null", element);
    assertNull("12.35 node incorrectly selected", element.attribute("selected"));
    assertNull("No id rendered", element.attribute("id"));
  }
Exemplo n.º 12
0
  public void testWithFloatCustom() throws Exception {
    PropertyEditor propertyEditor = new SimpleFloatEditor();
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(getTestBean(), COMMAND_NAME);
    errors.getPropertyAccessor().registerCustomEditor(Float.class, propertyEditor);
    exposeBindingResult(errors);

    this.tag.setPath("myFloat");

    Float[] array =
        new Float[] {
          new Float("12.30"), new Float("12.32"), new Float("12.34"), new Float("12.36"),
          new Float("12.38"), new Float("12.40"), new Float("12.42"), new Float("12.44"),
          new Float("12.46"), new Float("12.48")
        };

    this.tag.setItems(array);
    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getWriter().toString();
    assertTrue(output.startsWith("<select "));
    assertTrue(output.endsWith("</select>"));

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element rootElement = document.getRootElement();
    assertEquals("select", rootElement.getName());
    assertEquals("myFloat", rootElement.attribute("name").getValue());
    List children = rootElement.elements();
    assertEquals("Incorrect number of children", array.length, children.size());

    Element e = (Element) rootElement.selectSingleNode("option[text() = '12.34f']");
    assertEquals("'12.34' node not selected", "selected", e.attribute("selected").getValue());

    e = (Element) rootElement.selectSingleNode("option[text() = '12.32f']");
    assertNull("'12.32' node incorrectly selected", e.attribute("selected"));
  }
Exemplo n.º 13
0
  void validateCompanies(List<VacancyTemplate> vacancyTemplates) {
    List<Company> companies = new ArrayList<>();
    Set<String> companyCaptions = new HashSet<String>();
    vacancyTemplates.forEach(
        vacancyTemplate -> companyCaptions.add(vacancyTemplate.getCompanyCaption()));

    companyCaptions.forEach(
        s -> {
          Company company = companyService.findByCaption(s);
          if (company == null) {
            company = new Company();
            company.setCaption(s);

            BeanPropertyBindingResult result = new BeanPropertyBindingResult(company, s);

            ValidationUtils.invokeValidator(validator, company, result);
            if (result.hasErrors()) {
              List<ObjectError> errors = result.getAllErrors();
              StringBuilder builder = new StringBuilder();
              builder.append(
                  String.format(
                      "Validate company '%s' . No of validation errors: %s", s, errors.size()));
              errors.forEach(
                  objectError -> {
                    builder.append("\n");
                    builder.append(objectError.getDefaultMessage());
                  });
              log.error(builder.toString());
            } else {
              companies.add(company);
            }
          }
        });

    saveAllCompanies(companies);
  }
  public void testCollectionOfPetsWithEditor() throws Exception {
    this.tag.setPath("pets");
    List allPets = new ArrayList();
    allPets.add(new ItemPet("Rudiger"));
    allPets.add(new ItemPet("Spot"));
    allPets.add(new ItemPet("Checkers"));
    allPets.add(new ItemPet("Fluffy"));
    allPets.add(new ItemPet("Mufty"));
    this.tag.setItems(allPets);
    this.tag.setItemLabel("label");
    this.tag.setId("myId");

    BeanPropertyBindingResult bindingResult =
        new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
    PropertyEditorSupport editor = new ItemPet.CustomEditor();
    bindingResult.getPropertyEditorRegistry().registerCustomEditor(ItemPet.class, editor);
    getPageContext()
        .getRequest()
        .setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);

    int result = this.tag.doStartTag();
    assertEquals(Tag.SKIP_BODY, result);

    String output = getOutput();

    // wrap the output so it is valid XML
    output = "<doc>" + output + "</doc>";

    SAXReader reader = new SAXReader();
    Document document = reader.read(new StringReader(output));
    Element spanElement1 = (Element) document.getRootElement().elements().get(0);
    Element checkboxElement1 = (Element) spanElement1.elements().get(0);
    assertEquals("input", checkboxElement1.getName());
    assertEquals("checkbox", checkboxElement1.attribute("type").getValue());
    assertEquals("pets", checkboxElement1.attribute("name").getValue());
    assertEquals("checked", checkboxElement1.attribute("checked").getValue());
    assertEquals("Rudiger", checkboxElement1.attribute("value").getValue());
    assertEquals("RUDIGER", spanElement1.getStringValue());
    Element spanElement2 = (Element) document.getRootElement().elements().get(1);
    Element checkboxElement2 = (Element) spanElement2.elements().get(0);
    assertEquals("input", checkboxElement2.getName());
    assertEquals("checkbox", checkboxElement2.attribute("type").getValue());
    assertEquals("pets", checkboxElement2.attribute("name").getValue());
    assertEquals("checked", checkboxElement2.attribute("checked").getValue());
    assertEquals("Spot", checkboxElement2.attribute("value").getValue());
    assertEquals("SPOT", spanElement2.getStringValue());
    Element spanElement3 = (Element) document.getRootElement().elements().get(2);
    Element checkboxElement3 = (Element) spanElement3.elements().get(0);
    assertEquals("input", checkboxElement3.getName());
    assertEquals("checkbox", checkboxElement3.attribute("type").getValue());
    assertEquals("pets", checkboxElement3.attribute("name").getValue());
    assertNull("not checked", checkboxElement3.attribute("checked"));
    assertEquals("Checkers", checkboxElement3.attribute("value").getValue());
    assertEquals("CHECKERS", spanElement3.getStringValue());
    Element spanElement4 = (Element) document.getRootElement().elements().get(3);
    Element checkboxElement4 = (Element) spanElement4.elements().get(0);
    assertEquals("input", checkboxElement4.getName());
    assertEquals("checkbox", checkboxElement4.attribute("type").getValue());
    assertEquals("pets", checkboxElement4.attribute("name").getValue());
    assertEquals("checked", checkboxElement4.attribute("checked").getValue());
    assertEquals("Fluffy", checkboxElement4.attribute("value").getValue());
    assertEquals("FLUFFY", spanElement4.getStringValue());
    Element spanElement5 = (Element) document.getRootElement().elements().get(4);
    Element checkboxElement5 = (Element) spanElement5.elements().get(0);
    assertEquals("input", checkboxElement5.getName());
    assertEquals("checkbox", checkboxElement5.attribute("type").getValue());
    assertEquals("pets", checkboxElement5.attribute("name").getValue());
    assertEquals("checked", checkboxElement5.attribute("checked").getValue());
    assertEquals("Mufty", checkboxElement5.attribute("value").getValue());
    assertEquals("MUFTY", spanElement5.getStringValue());
  }
  public void testNew() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request = new MockHttpServletRequest("GET", "/workCodeForm.html");
    MockHttpServletResponse response = new MockHttpServletResponse();
    simpleDispatcherServlet.service(request, response);
    ModelAndView mv = child.handleRequest(request, response);

    Map m = mv.getModel();
    log.debug("m = " + m);
    WorkCodeFormBacking backing = (WorkCodeFormBacking) m.get("workCodeFormBacking");
    log.debug(Constants.toReflexString(backing));

    MockPageContext ctx = new MockPageContext();
    Iterator i = m.keySet().iterator();
    while (i.hasNext()) {
      String key = (String) i.next();
      ctx.setAttribute(key, m.get(key));
    }

    RequestContext r = new RequestContext(request, m);

    BindStatus b = r.getBindStatus("workCodeFormBacking.workCode.description");
    log.debug("expression = " + b.getExpression());
    log.debug("value = " + b.getValue());

    String description =
        (String)
            ExpressionEvaluationUtils.evaluate(
                "test", "${workCodeFormBacking.workCode.description}", String.class, ctx);

    // request.addParameter(name, description);
    String parttime =
        (String)
            ExpressionEvaluationUtils.evaluate(
                "test", "${workCodeFormBacking.workCode.parttime}", String.class, ctx);
    String code =
        (String)
            ExpressionEvaluationUtils.evaluate(
                "test", "${workCodeFormBacking.workCode.code}", String.class, ctx);
    String id =
        (String)
            ExpressionEvaluationUtils.evaluate(
                "test", "${workCodeFormBacking.workCode.id}", String.class, ctx);
    String save =
        (String)
            ExpressionEvaluationUtils.evaluate(
                "test", "${workCodeFormBacking.save}", String.class, ctx);

    log.debug("description = " + description);
    log.debug("parttime = " + parttime);
    log.debug("code = " + code);
    log.debug("id = " + id);
    log.debug("save = " + save);

    HashMap newMap = new HashMap();
    newMap.put(
        r.getBindStatus("workCodeFormBacking.workCode.description").getExpression(), description);
    newMap.put(r.getBindStatus("workCodeFormBacking.workCode.parttime").getExpression(), parttime);
    newMap.put(r.getBindStatus("workCodeFormBacking.workCode.code").getExpression(), code);
    newMap.put(r.getBindStatus("workCodeFormBacking.workCode.id").getExpression(), id);
    newMap.put(r.getBindStatus("workCodeFormBacking.save").getExpression(), "save");

    request = new MockHttpServletRequest("POST", "/workCodeForm.html");
    i = newMap.keySet().iterator();
    while (i.hasNext()) {
      String key = (String) i.next();
      log.debug("add parameter " + key + "  " + newMap.get(key));
      request.addParameter(key, (String) newMap.get(key));
    }
    mv = child.handleRequest(request, response);
    m = mv.getModel();
    log.debug("m = " + m);
    BeanPropertyBindingResult br =
        (BeanPropertyBindingResult)
            m.get("org.springframework.validation.BindingResult.workCodeFormBacking");
    log.debug("field errors " + br.getFieldErrorCount());
    log.debug("errors " + br.getErrorCount());
    assertTrue(br.getFieldError("workCode.code") != null);
    assertTrue(br.getFieldError("workCode.description") != null);
    backing = (WorkCodeFormBacking) m.get("workCodeFormBacking");
    log.debug(response.getErrorMessage());
    log.debug(Constants.toReflexString(backing));
    log.debug("view = " + mv.getViewName());
    assertTrue("workCodeForm".equals(mv.getViewName()));
  }
Exemplo n.º 16
0
  @Test
  public void webMvcConfigurerExtensionHooks() throws Exception {

    StaticWebApplicationContext appCxt = new StaticWebApplicationContext();
    appCxt.setServletContext(new MockServletContext(new FileSystemResourceLoader()));
    appCxt.registerSingleton("controller", TestController.class);

    WebConfig webConfig = new WebConfig();
    webConfig.setApplicationContext(appCxt);
    webConfig.setServletContext(appCxt.getServletContext());

    String actual = webConfig.mvcConversionService().convert(new TestBean(), String.class);
    assertEquals("converted", actual);

    RequestMappingHandlerAdapter adapter = webConfig.requestMappingHandlerAdapter();
    assertEquals(1, adapter.getMessageConverters().size());

    ConfigurableWebBindingInitializer initializer =
        (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
    assertNotNull(initializer);

    BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(null, "");
    initializer.getValidator().validate(null, bindingResult);
    assertEquals("invalid", bindingResult.getAllErrors().get(0).getCode());

    @SuppressWarnings("unchecked")
    List<HandlerMethodArgumentResolver> argResolvers =
        (List<HandlerMethodArgumentResolver>)
            new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers");
    assertEquals(1, argResolvers.size());

    @SuppressWarnings("unchecked")
    List<HandlerMethodReturnValueHandler> handlers =
        (List<HandlerMethodReturnValueHandler>)
            new DirectFieldAccessor(adapter).getPropertyValue("customReturnValueHandlers");
    assertEquals(1, handlers.size());

    HandlerExceptionResolverComposite composite =
        (HandlerExceptionResolverComposite) webConfig.handlerExceptionResolver();
    assertEquals(1, composite.getExceptionResolvers().size());

    RequestMappingHandlerMapping rmHandlerMapping = webConfig.requestMappingHandlerMapping();
    rmHandlerMapping.setApplicationContext(appCxt);
    HandlerExecutionChain chain =
        rmHandlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
    assertNotNull(chain.getInterceptors());
    assertEquals(2, chain.getInterceptors().length);
    assertEquals(LocaleChangeInterceptor.class, chain.getInterceptors()[0].getClass());
    assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass());

    AbstractHandlerMapping handlerMapping =
        (AbstractHandlerMapping) webConfig.viewControllerHandlerMapping();
    handlerMapping.setApplicationContext(appCxt);
    assertNotNull(handlerMapping);
    assertEquals(1, handlerMapping.getOrder());
    HandlerExecutionChain handler =
        handlerMapping.getHandler(new MockHttpServletRequest("GET", "/path"));
    assertNotNull(handler.getHandler());

    handlerMapping = (AbstractHandlerMapping) webConfig.resourceHandlerMapping();
    handlerMapping.setApplicationContext(appCxt);
    assertNotNull(handlerMapping);
    assertEquals(Integer.MAX_VALUE - 1, handlerMapping.getOrder());
    handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif"));
    assertNotNull(handler.getHandler());

    handlerMapping = (AbstractHandlerMapping) webConfig.defaultServletHandlerMapping();
    handlerMapping.setApplicationContext(appCxt);
    assertNotNull(handlerMapping);
    assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
    handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/anyPath"));
    assertNotNull(handler.getHandler());
  }
Exemplo n.º 17
0
  List<Vacancy> validateVacancies(List<VacancyTemplate> vacancyTemplates) {
    Set<String> vacancyURLs = new HashSet<>();
    List<Vacancy> vacancies = new ArrayList<>();
    for (VacancyTemplate vt : vacancyTemplates) {
      Company company = companyService.findByCaption(vt.getCompanyCaption());
      if (company == null)
        log.error(
            "Job missing: '{}'. Reason: company '{}' not found",
            vt.getVacancyCaption(),
            vt.getCompanyCaption());
      else if (!vacancyURLs.contains(vt.getVacancyUrl())) {

        String pathSegment;

        try {
          pathSegment =
              UriUtils.encodePathSegment(vt.getVacancyUrl(), WebUtils.DEFAULT_CHARACTER_ENCODING);
        } catch (UnsupportedEncodingException uee) {
          log.error(uee.toString());
          continue;
        }

        vacancyURLs.add(pathSegment);

        Vacancy vacancy = new Vacancy();
        vacancy.setId(pathSegment);
        vacancy.setCaption(vt.getVacancyCaption());
        vacancy.setUrl(vt.getVacancyUrl());
        vacancy.setPriceMax(vt.getPriceMax());
        vacancy.setPriceMin(vt.getPriceMin());
        vacancy.setRegistrationDate(vt.getRegistrationDate());
        vacancy.setCurrency(currencyService.findByCaption(vt.getCurrencyCaption()));
        vacancy.setSite(vt.getSite());
        vacancy.setCity(vt.getCity());
        vacancy.setCompany(company);

        BeanPropertyBindingResult result =
            new BeanPropertyBindingResult(vacancy, vacancy.getCaption());

        ValidationUtils.invokeValidator(validator, vacancy, result);
        if (result.hasErrors()) {
          List<ObjectError> errors = result.getAllErrors();

          StringBuilder builder = new StringBuilder();
          builder.append(
              String.format(
                  "Validate vacancy '%s' . No of validation errors: %s",
                  vacancy.getCaption(), errors.size()));
          errors.forEach(
              objectError -> {
                builder.append("\n");
                builder.append(objectError.getDefaultMessage());
              });
          log.error(builder.toString());
        } else {
          vacancies.add(vacancy);
        }
      }
    }

    return vacancies;
  }