Как установитьConstraintViolations в EditorDriver, используя возвращаемое значение вызова метода Validator Validate на стороне клиента

Используя GWT 2.5.0, я хотел бы использовать проверку на стороне клиента и редакторы. Я сталкиваюсь со следующей ошибкой при попытке передать ConstraintViolation java.util.Set в EditorDriver следующим образом.

Validator a = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Person>> b = a.validate(person);
editorDriver.setConstraintViolations(b);

The method setConstraintViolations(Iterable<ConstraintViolation<?>>) in the type EditorDriver<Person> is not applicable for the arguments (Set<ConstraintViolation<Person>>)

Единственное, что мне удалось найти, это ошибка 6270!

Ниже приведен пример, который вызывает PopUpDialog с редактором Person, который позволяет вам указать имя и проверить его на соответствие вашим аннотациям. Комментирование строки personDriver.setConstraintViolations(violations); в диалоговом окне PersonEditorDialog позволит вам запустить пример.

У меня недостаточно очков репутации, чтобы опубликовать изображение примера.

Классы


Человек

public class Person {

@NotNull(message = "You must have a name")

@Size(min = 3, message = "Your name must contain more than 3 characters")

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

Диалоговое окно редактора персон

public class PersonEditorDialog extends DialogBox implements Editor<Person> {

private static PersonEditorDialogUiBinder uiBinder = GWT
        .create(PersonEditorDialogUiBinder.class);

interface PersonEditorDialogUiBinder extends
        UiBinder<Widget, PersonEditorDialog> {
}

private Validator validator;

public PersonEditorDialog() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();
    setWidget(uiBinder.createAndBindUi(this));
}

interface Driver extends SimpleBeanEditorDriver<Person, PersonEditorDialog> {
};

@UiField
ValueBoxEditorDecorator<String> nameEditor;

@UiField
Button validateBtn;

private Driver personDriver;

@UiHandler("validateBtn")
public void handleValidate(ClickEvent e) {
    Person created = personDriver.flush();
    Set<ConstraintViolation<Person>> violations = validator
            .validate(created);
    if (!violations.isEmpty() || personDriver.hasErrors()) {
        StringBuilder violationMsg = new StringBuilder();
        for (Iterator<ConstraintViolation<Person>> iterator = violations.iterator(); iterator.hasNext();) {
            ConstraintViolation<Person> constraintViolation = (ConstraintViolation<Person>) iterator
                    .next();
            violationMsg.append(constraintViolation.getMessage() + ",");
        }
        Window.alert("Detected violations:" + violationMsg);
         personDriver.setConstraintViolations(violations);
    }
}

@Override
public void center() {
    personDriver = GWT.create(Driver.class);
    personDriver.initialize(this);
    personDriver.edit(new Person());
    super.center();
}
}

SampleValidationFactory

public final class SampleValidationFactory extends AbstractGwtValidatorFactory {

/**
 * Validator marker for the Validation Sample project. Only the classes and
 * groups listed in the {@link GwtValidation} annotation can be validated.
 */
@GwtValidation(Person.class)
public interface GwtValidator extends Validator {
}

@Override
public AbstractGwtValidator createValidator() {
    return GWT.create(GwtValidator.class);
}
}

РедакторВалидатионТест

public class EditorValidationTest implements EntryPoint {


/**
 * This is the entry point method.
 */
public void onModuleLoad() {
    PersonEditorDialog personEditorDialog = new PersonEditorDialog();
    personEditorDialog.center();
}
}

UiBinder

PersonEditorDialog.ui.xml

<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:e="urn:import:com.google.gwt.editor.ui.client">
<ui:style>
    .important {
        font-weight: bold;
    }
</ui:style>
<g:HTMLPanel>
    <g:Label>Enter your Name:</g:Label>
    <e:ValueBoxEditorDecorator ui:field="nameEditor">
        <e:valuebox>
            <g:TextBox />
        </e:valuebox>
    </e:ValueBoxEditorDecorator>
    <g:Button ui:field="validateBtn">Validate</g:Button>
</g:HTMLPanel>
</ui:UiBinder> 

Модуль ГВТ

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.0//EN"
"http://google-web-toolkit.googlecode.com/svn/tags/2.5.0/distro-source/core/src/gwt-module.dtd">
<module rename-to='editorvalidationtest'>
<inherits name='com.google.gwt.user.User' />
<inherits name='com.google.gwt.user.theme.clean.Clean' />
<inherits name="com.google.gwt.editor.Editor"/>

<!-- Validation module inherits -->

<inherits name="org.hibernate.validator.HibernateValidator" />
<replace-with
    class="com.test.client.SampleValidationFactory">
    <when-type-is class="javax.validation.ValidatorFactory" />
</replace-with>

<!-- Specify the app entry point class. -->
<entry-point class='com.test.client.EditorValidationTest' />

<!-- Specify the paths for translatable code -->
<source path='client' />
<source path='shared' />

</module>

Библиотеки, необходимые для пути к классам

  • спящий-валидатор-4.1.0.Final.jar
  • спящий-валидатор-4.1.0.Final-sources.jar
  • validation-api-1.0.0.GA.jar (в GWT SDK)
  • validation-api-1.0.0.GA-sources.jar (в GWT SDK)
  • slf4j-апи-1.6.1.jar
  • slf4j-log4j12-1.6.1.jar
  • log4j-1.2.16.jar

person asenec4    schedule 14.02.2013    source источник


Ответы (2)


Как обсуждалось в комментариях, следующее приведение было определено как допустимый обходной путь.

Set<?> test = violations; 
editorDriver.setConstraintViolations((Set<ConstraintViolation<?>>) test);
person asenec4    schedule 19.02.2013
comment
Лол, я нарушил этикет стека. Я решил, что для ясности стоит дать ответ как ответ. Я ценю помощь @koma. - person asenec4; 20.02.2013

Вот что я делаю снова и снова:

    List<ConstraintViolation<?>> adaptedViolations = new ArrayList<ConstraintViolation<?>>();
    for (ConstraintViolation<Person> violation : violations) {
        adaptedViolations.add(violation);
    }
    editorDriver.setConstraintViolations(adaptedViolations);

В драйвере определен общий тип с подстановочными знаками, и вы не можете передать нарушения типизированного ограничения.

person koma    schedule 14.02.2013
comment
Разве вы не можете просто бросить его вместо этого? Разве это не должно заставить его вести себя, а не копировать список? - person Colin Alworth; 15.02.2013
comment
вероятно ... короче и, скорее всего, более эффективно, хотя для полученного javascript компилятор может оптимизировать его; - person koma; 15.02.2013
comment
Компилятор удалит приведения, если вы попросите его об этом, см. -XdisableCastChecking на сайте разработчикам. .google.com/web-toolkit/doc/latest/ Он не может сделать то же самое для создания массива, копирования содержимого и т. д. - person Colin Alworth; 15.02.2013
comment
Единственное приведение, которое я нашел работающим, это следующее: Set‹?› тест = нарушения; editorDriver.setConstraintViolations((Set‹ConstraintViolation‹?›› тест); - person asenec4; 15.02.2013
comment
@asenec4, который должен это сделать и решить вашу проблему. Это совсем не элегантно, но работает; - person koma; 15.02.2013