Skip to content

Remove repeat hyphen #474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
Expand All @@ -43,6 +42,7 @@
import ru.mystamps.web.Url;
import ru.mystamps.web.controller.converter.annotation.Category;
import ru.mystamps.web.controller.converter.annotation.CurrentUser;
import ru.mystamps.web.controller.editor.ReplaceRepeatingSpacesEditor;
import ru.mystamps.web.dao.dto.LinkEntityDto;
import ru.mystamps.web.dao.dto.SeriesInfoDto;
import ru.mystamps.web.dao.dto.UrlEntityDto;
Expand All @@ -62,7 +62,9 @@ public class CategoryController {

@InitBinder("addCategoryForm")
protected void initBinder(WebDataBinder binder) {
StringTrimmerEditor editor = new StringTrimmerEditor(false);
// CheckStyle: ignore LineLength for next 1 line
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот почему у тебя тесты падать начали -- ты зря удалил этот эдитор -- он для другого и нужен здесь.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я добавил тримы непосредственно в реализацию кастомэдитора и все чеки прошли.
Возможно, я неверно трактовал эту проверку, но исходя из того что мы везде тримим пробелы, я решил это вынести.
И еще один момент, если мы оставим этот эдитор, то у нас не будет это все корректно работать , я пока не капнул почему, но моя догадка, что ЛУЧШЕ использовать только один эдитор.
Как ты считаешь ??

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ни разу не имел дел с более чем одним валидатором, поэтому придется тебе экспериментировать и проверять что/как можно, а что нельзя. Если смотреть с точки зрения принципа единой ответственности (SRP), то лучше держать проверки отдельно -- и реюзать проще и логика не "слипается".

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ну вот я и эксперементировал , и если делать два подряд - выполняется только последний......
Еще попробую покрутить, но пока такие результаты.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: Only one single registered custom editor per property path is supported. (c) http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/validation/DataBinder.html#registerCustomEditor-java.lang.Class-java.lang.String-java.beans.PropertyEditor-

Тогда надо либо попробовать какие-либо конвертеры использовать, либо использовать паттерн декоратор (и вкладывать один в другой).

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want to re-implement StringTrimmerEditor and don't re-use this class then we don't need this flags because we're not using them, right?

Then, implement our own editor that do a trimming and also replace hyphens. Hm. Not ideal, but we have tests after all, so we can refactor this any time.

And also add the comment why we're not using StringTrimmerEditor.

Copy link
Contributor Author

@bodom91 bodom91 Aug 29, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes , i will not use StringTrimEditor class , but i need use boolean .
I need it because we want separate functionality CustomEditor.
If we have true - trim String , if we have false or empty value - not trim String.
Do you agree ?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're going to add flag that always will have value true, right? As far I understand we'll use this converter for category and country names. For them we always need to trim the string, right?

And now I'm still don't understand why we need this flag.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not exactly ))
Maybe i do , and you will see ... )

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok.

// We can't use StringTrimmerEditor here because "only one single registered custom editor per property path is supported".
ReplaceRepeatingSpacesEditor editor = new ReplaceRepeatingSpacesEditor(true);
binder.registerCustomEditor(String.class, "name", editor);
binder.registerCustomEditor(String.class, "nameRu", editor);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
* Copyright (C) 2009-2016 Slava Semushin <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ru.mystamps.web.controller.editor;

import java.beans.PropertyEditorSupport;
import java.util.regex.Pattern;

import lombok.RequiredArgsConstructor;

/**
* @author Maxim Shestakov
*/
@RequiredArgsConstructor
public class ReplaceRepeatingSpacesEditor extends PropertyEditorSupport {
private static final Pattern REPEATING_SPACES = Pattern.compile("[ ]{2,}");
private final boolean performTrimming;

@Override
public void setAsText(String name) throws IllegalArgumentException {
String text = name;

if (performTrimming) {
text = name.trim();
}

if (text.contains(" ")) {
text = REPEATING_SPACES.matcher(text).replaceAll(" ");
}

setValue(text);
}

}
22 changes: 17 additions & 5 deletions src/main/java/ru/mystamps/web/model/AddCategoryForm.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import static ru.mystamps.web.validation.ValidationRules.CATEGORY_NAME_MAX_LENGTH;
import static ru.mystamps.web.validation.ValidationRules.CATEGORY_NAME_MIN_LENGTH;
import static ru.mystamps.web.validation.ValidationRules.CATEGORY_NAME_NO_HYPHEN_REGEXP;
import static ru.mystamps.web.validation.ValidationRules.CATEGORY_NAME_NO_REPEATING_HYPHENS_REGEXP;
import static ru.mystamps.web.validation.ValidationRules.CATEGORY_NAME_RU_REGEXP;

@Getter
Expand All @@ -44,7 +45,8 @@
Group.Level2.class,
Group.Level3.class,
Group.Level4.class,
Group.Level5.class
Group.Level5.class,
Group.Level6.class
})
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, don't modify code unless you have to.

public class AddCategoryForm implements AddCategoryDto {

Expand All @@ -67,13 +69,18 @@ public class AddCategoryForm implements AddCategoryDto {
message = "{category-name-en.invalid}",
groups = Group.Level3.class
),
@Pattern(
regexp = CATEGORY_NAME_NO_REPEATING_HYPHENS_REGEXP,
message = "{value.repeating_hyphen}",
groups = Group.Level4.class
),
@Pattern(
regexp = CATEGORY_NAME_NO_HYPHEN_REGEXP,
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, put this line to the same place.

message = "{value.hyphen}",
groups = Group.Level4.class
groups = Group.Level5.class
)
})
@UniqueCategoryName(lang = Lang.EN, groups = Group.Level5.class)
@UniqueCategoryName(lang = Lang.EN, groups = Group.Level6.class)
private String name;

@NotEmpty(groups = Group.Level1.class)
Expand All @@ -95,13 +102,18 @@ public class AddCategoryForm implements AddCategoryDto {
message = "{category-name-ru.invalid}",
groups = Group.Level3.class
),
@Pattern(
regexp = CATEGORY_NAME_NO_REPEATING_HYPHENS_REGEXP,
message = "{value.repeating_hyphen}",
groups = Group.Level4.class
),
@Pattern(
regexp = CATEGORY_NAME_NO_HYPHEN_REGEXP,
message = "{value.hyphen}",
groups = Group.Level4.class
groups = Group.Level5.class
)
})
@UniqueCategoryName(lang = Lang.RU, groups = Group.Level5.class)
@UniqueCategoryName(lang = Lang.RU, groups = Group.Level6.class)
private String nameRu;

}
3 changes: 3 additions & 0 deletions src/main/java/ru/mystamps/web/model/Group.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,8 @@ interface Level4 {

interface Level5 {
}

interface Level6 {
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public final class ValidationRules {
public static final String CATEGORY_NAME_EN_REGEXP = "[- a-zA-Z]+";
public static final String CATEGORY_NAME_RU_REGEXP = "[- а-яёА-ЯЁ]+";
public static final String CATEGORY_NAME_NO_HYPHEN_REGEXP = "[ \\p{L}]([- \\p{L}]+[ \\p{L}])*";
@SuppressWarnings({"PMD.LongVariable", "checkstyle:linelength"})
public static final String CATEGORY_NAME_NO_REPEATING_HYPHENS_REGEXP = "(?!.+[-]{2,}).+";

public static final int COUNTRY_NAME_MIN_LENGTH = 3;
public static final int COUNTRY_NAME_MAX_LENGTH = Db.Country.NAME_LENGTH;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ value.too-short = Value is less than allowable minimum of {min} characters
value.too-long = Value is greater than allowable maximum of {max} characters
value.invalid-length = Value length must be equals to {max} characters
value.hyphen = Value must not start or end with hyphen
value.repeating_hyphen = Value must not contain repetition of hyphen
value.empty = Value must not be empty

category-name-en.invalid = Category name must consist only latin letters, hyphen or spaces
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ value.too-short = Значение должно быть не менее {min}
value.too-long = Значение должно быть не более {max} символов
value.invalid-length = Значение должно быть длинной {max} символов
value.hyphen = Значение не должно начинаться или заканчиваться знаком дефиса
value.repeating_hyphen = Значение не должно содержать повторяющиеся знаки дефиса
value.empty = Значение не должно быть пустым

category-name-en.invalid = Название категории может содержать только латинские буквы, дефис или пробел
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,20 @@ public void categoryNameRuShouldNotEndsWithHyphen() {

assertThat(page).field("nameRu").hasError(tr("value.hyphen"));
}

@Test(groups = "invalid", dependsOnGroups = "std")
public void categoryNameEnShouldNotContainRepeatedHyphens() {
page.addCategory("te--st", TEST_CATEGORY_NAME_RU);

assertThat(page).field("name").hasError(tr("value.repeating_hyphen"));
}

@Test(groups = "invalid", dependsOnGroups = "std")
public void categoryNameRuShouldNotContainRepeatedHyphens() {
page.addCategory(TEST_CATEGORY_NAME_EN, "те--ст");

assertThat(page).field("nameRu").hasError(tr("value.repeating_hyphen"));
}

@Test(groups = "misc", dependsOnGroups = "std")
public void categoryNameEnShouldBeStripedFromLeadingAndTrailingSpaces() {
Expand All @@ -198,6 +212,20 @@ public void categoryNameRuShouldBeStripedFromLeadingAndTrailingSpaces() {

assertThat(page).field("nameRu").hasValue("т3ст");
}

@Test(groups = "misc", dependsOnGroups = "std")
public void categoryNameEnShouldReplaceRepeatedSpacesByOne() {
page.addCategory("t3 st", TEST_CATEGORY_NAME_RU);

assertThat(page).field("name").hasValue("t3 st");
}

@Test(groups = "misc", dependsOnGroups = "std")
public void categoryNameRuShouldReplaceRepeatedSpacesByOne() {
page.addCategory(TEST_CATEGORY_NAME_EN, "т3 ст");

assertThat(page).field("nameRu").hasValue("т3 ст");
}
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're grouping tests based on what they're doing while other tests are grouped on the order of the fields on the form.


@Test(groups = "logic", dependsOnGroups = { "std", "invalid", "valid", "misc" })
public void shouldBeRedirectedToPageWithInfoAboutCategoryAfterCreation() {
Expand Down