IMI-Application/src/main/java/de/vanitasvitae/imi/codes/CodeGenerator.java

48 lines
1.7 KiB
Java

package de.vanitasvitae.imi.codes;
import java.io.File;
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;
public class CodeGenerator {
private final FileRepository repository = new FileRepository(new File(".imicodes"));
public CodeGenerator() {
}
public List<SampleTubeCode> generateCodes(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;
}
}