63 lines
2.3 KiB
Java
63 lines
2.3 KiB
Java
package de.vanitasvitae.imi.codes;
|
|
|
|
import java.io.IOException;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
|
|
import de.vanitasvitae.imi.codes.input.InvalidOptionException;
|
|
import de.vanitasvitae.imi.codes.persistence.FileRepository;
|
|
import de.vanitasvitae.imi.codes.types.SampleTubeCode;
|
|
import de.vanitasvitae.imi.codes.types.SampleType;
|
|
import de.vanitasvitae.imi.codes.types.StudyNumber;
|
|
|
|
/**
|
|
* Class that generates {@link SampleTubeCode SampleTubeCodes}.
|
|
*/
|
|
public class CodeGenerator {
|
|
|
|
// Pls do not instantiate.
|
|
private CodeGenerator() {
|
|
|
|
}
|
|
|
|
/**
|
|
* Generate {@code numberOfCodes} new codes for samples of type {@code sampleType}, which are associated to study
|
|
* {@code studyNumber}.
|
|
*
|
|
* @param repository provides access to records of existing codes
|
|
* @param studyNumber number of the study
|
|
* @param sampleType type of the samples
|
|
* @param numberOfCodes number of codes to be generated
|
|
*
|
|
* @return list of {@link SampleTubeCode SampleTubeCodes}
|
|
*
|
|
* @throws InvalidOptionException if too many codes would be generated.
|
|
* @throws IOException if IO goes wrong reading or writing sample code records.
|
|
*/
|
|
public static List<SampleTubeCode> generateCodes(FileRepository repository, StudyNumber studyNumber, SampleType sampleType, int numberOfCodes)
|
|
throws InvalidOptionException, IOException {
|
|
List<SampleTubeCode> codes = new ArrayList<>();
|
|
|
|
// Read the next sample code from file
|
|
int nextSampleCode = repository.nextSampleCode(studyNumber);
|
|
|
|
int nextTotal = nextSampleCode + numberOfCodes;
|
|
// Check, if we'd have an overflow of sample numbers
|
|
// We check like this to prevent integer overflows
|
|
if (nextSampleCode > 9999 || numberOfCodes > 9999 || nextTotal - 1 > 9999) {
|
|
throw new InvalidOptionException("Study " + studyNumber + "would have too many sample tubes" +
|
|
" (" + (nextTotal - 1) + "). Aborting.");
|
|
}
|
|
|
|
// Write back the number of the next sample number that should be generated next time
|
|
repository.writeNextSampleCode(studyNumber, nextSampleCode + numberOfCodes);
|
|
|
|
// Generate codes
|
|
for (int i = 0; i < numberOfCodes; i++) {
|
|
codes.add(new SampleTubeCode(studyNumber, sampleType, nextSampleCode + i));
|
|
}
|
|
|
|
return codes;
|
|
}
|
|
}
|