Skip to content

Commit

Permalink
Postfach.validate(String) added
Browse files Browse the repository at this point in the history
  • Loading branch information
oboehm committed Jan 21, 2018
1 parent 557e10d commit 08fb116
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 3 deletions.
44 changes: 41 additions & 3 deletions src/main/java/de/jfachwert/post/Postfach.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,12 @@
*/
package de.jfachwert.post;

import de.jfachwert.*;
import de.jfachwert.Fachwert;
import de.jfachwert.pruefung.exception.InvalidValueException;
import org.apache.commons.lang3.StringUtils;

import java.math.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Optional;

/**
* Ein Postfach besteht aus einer Nummer ohne fuehrende Nullen und einer
Expand Down Expand Up @@ -73,6 +74,43 @@ public Postfach(BigInteger nummer, Ort ort) {
validate(nummer, ort);
}

/**
* Zerlegt das uebergebene Postfach in seine Einzelteile und validiert sie.
* Folgende Heuristiken werden fuer die Zerlegung herangezogen:
* <ul>
* <li>Format ist "Postfach, Ort" oder nur "Ort" (mit PLZ)</li>
* <li>Postfach ist vom Ort durch Komma oder Zeilenvorschub getrennt</li>
* </ul>
*
* @param postfach z.B. "Postfach 98765, 12345 Entenhausen"
*/
public static void validate(String postfach) {
String[] lines = split(postfach);
if (!lines[0].isEmpty()) {
toNumber(lines[0]);
}
Ort ort = new Ort(lines[1]);
if (!ort.getPLZ().isPresent()) {
throw new InvalidValueException(postfach, "postal_code");
}
}

private static String[] split(String postfach) {
String[] lines = StringUtils.trimToEmpty(postfach).split("[,\\n$]");
String[] splitted = { "", lines[0]};
if (lines.length == 2) {
splitted = lines;
} else if (lines.length > 2) {
throw new InvalidValueException(postfach, "post_office_box");
}
return lines;
}

private static BigInteger toNumber(String number) {
String unformatted = StringUtils.replaceAll(number, "Postfach|\\s+", "");
return new BigInteger(unformatted);
}

/**
* Validiert das uebergebene Postfach auf moegliche Fehler.
*
Expand Down
9 changes: 9 additions & 0 deletions src/test/java/de/jfachwert/post/PostfachTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,13 @@ public void testPostfachOhneNummer() {
assertThat(postfach.toString(), not(containsString("null")));
}

/**
* Test-Methode fuer {@link Postfach#validate(String)}.
*/
@Test
public void testValidate() {
String postfach = "Postfach 12 34 56\n12350 Musterdorf";
Postfach.validate(postfach);
}

}

0 comments on commit 08fb116

Please sign in to comment.