package de.vanitasvitae.imi.codes; import java.io.File; import java.util.regex.Pattern; public class InputValidator { // Allowed characters public static final String REGEX_ALPHABET = "[a-zA-Z0-9]"; public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; /* 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(REGEX_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(REGEX_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; } /** * Validate, that the user-provided path is writable and that any parent folders exist. * Otherwise throw a {@link InvalidOptionException}. * * @param path file path (absolut or relative) as a string. * @return file * * @throws InvalidOptionException in case any parent folder does not exist, the path points to a directory or the * destination is not writable. */ public static File validateOutputPath(String path) throws InvalidOptionException { // TODO return null; } }