77 lines
2.6 KiB
Java
77 lines
2.6 KiB
Java
package de.vanitasvitae.imi.codes;
|
|
|
|
import java.util.regex.Pattern;
|
|
|
|
public class InputValidator {
|
|
|
|
// Allowed characters
|
|
public static final String ALPHABET = "[a-zA-Z0-9]";
|
|
|
|
/*
|
|
REGEX pattern for study numbers. Allowed are all 3-letter numbers from the alphabet [a-zA-Z0-9].
|
|
*/
|
|
private static final Pattern STUDY_NUMBER_MATCHER = Pattern.compile(ALPHABET+"{3}");
|
|
|
|
/*
|
|
REGEX pattern for sample numbers. Allowed are four-letter numbers from the alphabet [a-zA-Z0-9].
|
|
*/
|
|
private static final Pattern SAMPLE_NUMBER_MATCHER = Pattern.compile(ALPHABET+"{4}");
|
|
|
|
/**
|
|
* Validate a given study number. Valid study numbers are 3-letter codes from the alphabet [a-zA-Z0-9].
|
|
*
|
|
* @param in input String
|
|
* @return unmodified input String if it matches.
|
|
*
|
|
* @throws InvalidOptionException if the input String doesn't match the regex.
|
|
*/
|
|
public static String validateStudyNumber(String in) throws InvalidOptionException {
|
|
if (!STUDY_NUMBER_MATCHER.matcher(in).matches()) {
|
|
throw new InvalidOptionException("Study number must be a three digit number from the alphabet [a-zA-Z0-9].");
|
|
}
|
|
|
|
return in;
|
|
}
|
|
|
|
/**
|
|
* Validate a given sample type. Valid types are found in {@link SampleType}.#
|
|
*
|
|
* @param in input String
|
|
* @return parsed {@link SampleType}.
|
|
*
|
|
* @throws InvalidOptionException if the given String doesn't match a {@link SampleType}.
|
|
* @throws NullPointerException in case the given String is {@code null}.
|
|
*/
|
|
public static SampleType validateSampleType(String in) throws InvalidOptionException {
|
|
try {
|
|
return SampleType.getEnum(in);
|
|
} catch (IllegalArgumentException e) {
|
|
String message = "Invalid sample type \"" + in + "\".";
|
|
throw new InvalidOptionException(message, e);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Validate, that the user provided number of codes to be generated is an integer greater than 0.
|
|
*
|
|
* @param in input String
|
|
* @return number of codes to be generated.
|
|
*
|
|
* @throws InvalidOptionException in case the input string is
|
|
*/
|
|
public static int validateNumberOfCodes(String in) throws InvalidOptionException {
|
|
int i;
|
|
try {
|
|
i = Integer.parseInt(in);
|
|
} catch (NumberFormatException e) {
|
|
throw new InvalidOptionException("Invalid input \"" + in + "\". Please enter a positive number.", e);
|
|
}
|
|
|
|
if (i <= 0) {
|
|
throw new InvalidOptionException("Number of generated codes must be greater than 0.");
|
|
}
|
|
|
|
return i;
|
|
}
|
|
}
|