From 83610f195fa8deeece57aca09a5aa23671877a34 Mon Sep 17 00:00:00 2001 From: Dario Date: Sat, 27 Jul 2024 00:02:31 +0200 Subject: [PATCH] parameter rework, logging and exception handling --- .../ucsd/sbrg/ModelPolisherCLILauncher.java | 59 +++--- .../edu/ucsd/sbrg/ModelPolisherOptions.java | 18 +- .../java/edu/ucsd/sbrg/ModelValidator.java | 67 ++---- .../ucsd/sbrg/ModelValidatorException.java | 17 ++ .../sbrg/annotation/AbstractAnnotator.java | 10 +- .../sbrg/annotation/AnnotationException.java | 8 + .../annotation/adb/ADBReactionsAnnotator.java | 13 +- .../sbrg/annotation/adb/ADBSBMLAnnotator.java | 4 +- .../annotation/adb/ADBSpeciesAnnotator.java | 13 +- .../annotation/adb/AbstractADBAnnotator.java | 5 +- .../bigg/AbstractBiGGAnnotator.java | 20 +- .../bigg/BiGGAnnotationException.java | 17 ++ .../annotation/bigg/BiGGAnnotationUtils.java | 6 - .../annotation/bigg/BiGGCVTermAnnotator.java | 3 +- .../bigg/BiGGCompartmentsAnnotator.java | 9 +- .../bigg/BiGGDocumentNotesProcessor.java | 13 +- .../annotation/bigg/BiGGModelAnnotator.java | 5 +- .../bigg/BiGGPublicationsAnnotator.java | 3 +- .../bigg/BiGGReactionsAnnotator.java | 32 +-- .../annotation/bigg/BiGGSBMLAnnotator.java | 4 +- .../annotation/bigg/BiGGSpeciesAnnotator.java | 54 ++--- .../annotation/bigg/fbc/BiGGFBCAnnotator.java | 3 +- .../bigg/fbc/BiGGGeneProductAnnotator.java | 22 +- .../java/edu/ucsd/sbrg/db/adb/AnnotateDB.java | 11 +- .../java/edu/ucsd/sbrg/db/bigg/BiGGDB.java | 110 ++++------ .../java/edu/ucsd/sbrg/db/bigg/BiGGId.java | 12 +- .../java/edu/ucsd/sbrg/io/CombineArchive.java | 119 +++++------ .../sbrg/io/DeleteOnCloseFileInputStream.java | 36 ++++ .../java/edu/ucsd/sbrg/io/ModelReader.java | 38 ++-- .../ucsd/sbrg/io/ModelReaderException.java | 17 ++ .../java/edu/ucsd/sbrg/io/ModelWriter.java | 190 +++++++++++++----- .../ucsd/sbrg/io/ModelWriterException.java | 38 ++++ .../java/edu/ucsd/sbrg/io/SBMLFileUtils.java | 4 +- .../sbrg/io/parsers/cobra/MatlabParser.java | 26 +-- .../ucsd/sbrg/io/parsers/json/JSONParser.java | 26 +-- .../parameters/CommandLineParameters.java | 20 +- .../sbrg/parameters/OutputParameters.java | 55 ----- .../edu/ucsd/sbrg/parameters/Parameters.java | 14 +- .../ucsd/sbrg/polishing/AbstractPolisher.java | 6 + .../sbrg/polishing/AnnotationPolisher.java | 7 + .../sbrg/polishing/CompartmentPolisher.java | 10 +- .../ucsd/sbrg/polishing/ModelPolisher.java | 10 +- .../sbrg/polishing/ParametersPolisher.java | 7 + .../sbrg/polishing/ReactionsPolisher.java | 20 +- .../edu/ucsd/sbrg/polishing/SBMLPolisher.java | 11 +- .../ucsd/sbrg/polishing/SpeciesPolisher.java | 20 +- .../edu/ucsd/sbrg/polishing/UnitPolisher.java | 45 +++-- .../ucsd/sbrg/polishing/fbc/FBCPolisher.java | 9 +- .../polishing/fbc/FluxObjectivesPolisher.java | 6 + .../polishing/fbc/GeneProductsPolisher.java | 8 +- .../polishing/fbc/StrictnessPredicate.java | 5 + .../sbrg/reporting/PolisherProgressBar.java | 3 +- .../ucsd/sbrg/reporting/ProgressUpdate.java | 2 +- .../edu/ucsd/sbrg/reporting/ReportType.java | 2 +- .../java/edu/ucsd/sbrg/util/GPRParser.java | 16 +- src/main/java/edu/ucsd/sbrg/util/SBMLFix.java | 29 +-- src/test/java/edu/ucsd/sbrg/TestUtils.java | 1 - .../bigg/BiGGCompartmentsAnnotatorTest.java | 5 +- .../bigg/BiGGModelAnnotatorTest.java | 4 +- .../bigg/BiGGReactionsAnnotatorTest.java | 3 +- .../bigg/BiGGSBMLAnnotatorTest.java | 5 +- .../bigg/BiGGSpeciesAnnotatorTest.java | 11 +- .../edu/ucsd/sbrg/db/bigg/BiGGDBTest.java | 7 +- .../sbrg/parameters/ParametersParserTest.java | 8 +- .../edu/ucsd/sbrg/parameters/parameters.json | 6 +- 65 files changed, 789 insertions(+), 598 deletions(-) create mode 100644 src/main/java/edu/ucsd/sbrg/ModelValidatorException.java create mode 100644 src/main/java/edu/ucsd/sbrg/annotation/AnnotationException.java create mode 100644 src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationException.java delete mode 100644 src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationUtils.java create mode 100644 src/main/java/edu/ucsd/sbrg/io/DeleteOnCloseFileInputStream.java create mode 100644 src/main/java/edu/ucsd/sbrg/io/ModelReaderException.java create mode 100644 src/main/java/edu/ucsd/sbrg/io/ModelWriterException.java delete mode 100644 src/main/java/edu/ucsd/sbrg/parameters/OutputParameters.java diff --git a/src/main/java/edu/ucsd/sbrg/ModelPolisherCLILauncher.java b/src/main/java/edu/ucsd/sbrg/ModelPolisherCLILauncher.java index 31c3fbd6..f6cbd69b 100644 --- a/src/main/java/edu/ucsd/sbrg/ModelPolisherCLILauncher.java +++ b/src/main/java/edu/ucsd/sbrg/ModelPolisherCLILauncher.java @@ -8,6 +8,7 @@ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; +import java.sql.SQLException; import java.util.Calendar; import java.util.LinkedList; import java.util.List; @@ -15,18 +16,13 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Logger; -import javax.xml.stream.XMLStreamException; - +import edu.ucsd.sbrg.annotation.AnnotationException; import edu.ucsd.sbrg.annotation.adb.ADBSBMLAnnotator; import edu.ucsd.sbrg.annotation.bigg.BiGGSBMLAnnotator; +import edu.ucsd.sbrg.io.*; import edu.ucsd.sbrg.parameters.CommandLineParameters; import edu.ucsd.sbrg.db.adb.AnnotateDB; import edu.ucsd.sbrg.db.bigg.BiGGDB; -import edu.ucsd.sbrg.io.IOOptions; -import edu.ucsd.sbrg.io.ModelReader; -import edu.ucsd.sbrg.io.ModelWriter; -import edu.ucsd.sbrg.io.SBMLFileUtils; -import edu.ucsd.sbrg.parameters.OutputParameters; import edu.ucsd.sbrg.polishing.SBMLPolisher; import edu.ucsd.sbrg.reporting.PolisherProgressBar; import edu.ucsd.sbrg.reporting.ProgressInitialization; @@ -62,7 +58,7 @@ * - HTML tag correction in SBML files. * - SBML document validation and conversion. * - Annotation of models using external databases. - * - Output management including file writing, COMBINE archive creation, and compression. + * - Output management including file writing, COMBINE archive creation, and outputType. *

* This class also handles error logging and provides detailed logging of the processing steps. * @@ -118,12 +114,7 @@ public ModelPolisherCLILauncher(String... args) { public void commandLineMode(AppConf appConf) { SBProperties args = appConf.getCmdArgs(); - try { - parameters = new CommandLineParameters(args); - } catch (IllegalArgumentException exc1) { - throw new IllegalArgumentException(exc1.getLocalizedMessage()); - } - + parameters = new CommandLineParameters(args); registry = new IdentifiersOrg(); if (parameters.annotationParameters().biggAnnotationParameters().annotateWithBiGG()) { @@ -136,7 +127,7 @@ public void commandLineMode(AppConf appConf) { try { var input = parameters.input(); - var output = parameters.outputParameters().outputFile(); + var output = parameters.output(); // Check if the input exists, throw an exception if it does not if (!input.exists()) { @@ -154,10 +145,18 @@ public void commandLineMode(AppConf appConf) { // Ensure the output directory or file's parent directory exists SBMLFileUtils.checkCreateOutDir(output); - batchProcess(input, parameters.outputParameters().outputFile()); + batchProcess(input, parameters.output()); - } catch (XMLStreamException | IOException exc) { - exc.printStackTrace(); + } catch (ModelReaderException | ModelValidatorException | ModelWriterException | IOException | + AnnotationException e) { + // TODO: produce some user-friendly output and log to a file that can be provided for trouble-shooting + throw new RuntimeException(e); + } catch (IllegalArgumentException exc1) { + // TODO: produce some user-friendly output and log to a file that can be provided for trouble-shooting + throw new IllegalArgumentException(exc1.getLocalizedMessage()); + } catch (SQLException e) { + // TODO: produce some user-friendly output and log to a file that can be provided for trouble-shooting + throw new RuntimeException(e); } } @@ -166,12 +165,9 @@ public void commandLineMode(AppConf appConf) { * Processes the specified input and output paths. If the input is a directory, it recursively processes each file within. * * @param input Path to the input file or directory to be processed. This should correspond to {@link CommandLineParameters#input()}. - * @param output Path to the output file or directory where processed files should be saved. - * This should correspond to {@link OutputParameters#outputFile()}. - * @throws IOException if the input file or directory does not exist, or if no files are found within the directory. - * @throws XMLStreamException if an error occurs during file processing, propagated from {@link ModelPolisherCLILauncher#processFile(File, File)}. + * @param output Path to the output file or directory where processed files should be saved. This should correspond to {@link CommandLineParameters#output()}. */ - private void batchProcess(File input, File output) throws IOException, XMLStreamException { + private void batchProcess(File input, File output) throws ModelReaderException, ModelWriterException, ModelValidatorException, AnnotationException, SQLException { // If the input is a directory, process each file within it if (input.isDirectory()) { File[] files = input.listFiles(); @@ -195,7 +191,7 @@ private void batchProcess(File input, File output) throws IOException, XMLStream } - private void processFile(File input, File output) throws XMLStreamException, IOException { + private void processFile(File input, File output) throws ModelReaderException, ModelWriterException, ModelValidatorException, AnnotationException, SQLException { long startTime = System.currentTimeMillis(); SBMLDocument doc = new ModelReader(parameters.sboParameters(), registry).read(input); @@ -214,7 +210,10 @@ private void processFile(File input, File output) throws XMLStreamException, IOE o.initialize(new ProgressInitialization(count)); } - new SBMLPolisher(parameters.polishingParameters(), parameters.sboParameters(), registry, polishingObservers).polish(doc); + new SBMLPolisher( + parameters.polishingParameters(), + parameters.sboParameters(), + registry, polishingObservers).polish(doc); for (var o : polishingObservers) { o.finish(null); @@ -227,8 +226,8 @@ private void processFile(File input, File output) throws XMLStreamException, IOE } if (parameters.annotationParameters().biggAnnotationParameters().annotateWithBiGG()) { - new BiGGSBMLAnnotator(bigg, parameters.annotationParameters().biggAnnotationParameters(), parameters.sboParameters(), - registry, annotationObservers).annotate(doc); + new BiGGSBMLAnnotator(bigg, parameters.annotationParameters().biggAnnotationParameters(), parameters.sboParameters(), + registry, annotationObservers).annotate(doc); } if (parameters.annotationParameters().adbAnnotationParameters().addADBAnnotations()) { @@ -239,12 +238,12 @@ private void processFile(File input, File output) throws XMLStreamException, IOE o.finish(null); } - new ModelWriter(parameters.outputParameters()).write(doc, output, getVersionNumber()); + output = new ModelWriter(parameters.outputType()).write(doc, output); if (parameters.SBMLValidation()) { - var mv = new ModelValidator(parameters.outputParameters()); + var mv = new ModelValidator(); // use offline validation - mv.validate(output, false); + mv.validate(output); } // Log the time taken to process the file diff --git a/src/main/java/edu/ucsd/sbrg/ModelPolisherOptions.java b/src/main/java/edu/ucsd/sbrg/ModelPolisherOptions.java index e8fa3c13..a863c51d 100644 --- a/src/main/java/edu/ucsd/sbrg/ModelPolisherOptions.java +++ b/src/main/java/edu/ucsd/sbrg/ModelPolisherOptions.java @@ -24,20 +24,20 @@ public interface ModelPolisherOptions extends KeyProvider { /** * @author Andreas Dräger */ - enum Compression { + enum OutputType { - GZIP("gz"), - NONE("none"), - ZIP("zip"); + SBML("xml"), + JSON("json"), + COMBINE("combine"); @JsonValue private final String extension; - Compression() { - this(null); + OutputType() { + this(null); } - Compression(String extension) { + OutputType(String extension) { this.extension = extension; } @@ -74,8 +74,8 @@ public String getFileExtension() { * so, which archive type should be used. */ @SuppressWarnings("unchecked") - Option COMPRESSION_TYPE = - new Option<>("COMPRESSION_TYPE", Compression.class, MESSAGES.getString("COMPR_DESC"), Compression.NONE); + Option OUTPUT_TYPE = + new Option<>("OUTPUT_TYPE", OutputType.class, MESSAGES.getString("COMPR_DESC"), OutputType.SBML); /** * This XHTML file defines alternative document notes and makes them * exchangeable. diff --git a/src/main/java/edu/ucsd/sbrg/ModelValidator.java b/src/main/java/edu/ucsd/sbrg/ModelValidator.java index c7501b9e..054f379b 100644 --- a/src/main/java/edu/ucsd/sbrg/ModelValidator.java +++ b/src/main/java/edu/ucsd/sbrg/ModelValidator.java @@ -2,80 +2,39 @@ import de.zbit.io.ZIPUtils; import de.zbit.util.ResourceManager; -import edu.ucsd.sbrg.parameters.OutputParameters; import org.sbml.jsbml.SBMLDocument; import org.sbml.jsbml.SBMLError; import org.sbml.jsbml.SBMLErrorLog; import org.sbml.jsbml.SBMLReader; -import org.sbml.jsbml.validator.SBMLValidator; import org.sbml.jsbml.validator.offline.LoggingValidationContext; import javax.xml.stream.XMLStreamException; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; +import java.io.*; import java.util.ResourceBundle; import java.util.logging.Logger; import static java.text.MessageFormat.format; public class ModelValidator { - /** - * Bundle for ModelPolisher logger messages - */ private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); - /** - * A {@link Logger} for this class. - */ private static final Logger logger = Logger.getLogger(ModelValidator.class.getName()); - private final OutputParameters parameters; - public ModelValidator(OutputParameters parameters) { - this.parameters = parameters; - } - /** - * Validates an SBML file either online or offline based on the provided parameters. - * Online validation refers to checking the file against a remote service or database, using specific parameters for the validation process. - * Offline validation involves reading the file locally, handling different compression formats if necessary, and validating the SBML document against local constraints. - * Errors encountered during the validation process are logged for further analysis. - * - * @param outputFile The file object of the SBML file to be validated. - * @param online A boolean flag indicating whether to perform online (true) or offline (false) validation. - */ - public void validate(File outputFile, boolean online) { - String fileExtension = parameters.compression().getFileExtension(); - String filename = outputFile.getAbsolutePath() + "." + fileExtension; + public void validate(File outputFile) throws ModelValidatorException { + try { + String filename = outputFile.getAbsolutePath(); - if (online) { - logger.info(format(MESSAGES.getString("VAL_ONLINE"), filename)); - String output = "xml"; - String offcheck = "p,u"; - Map parameters = new HashMap<>(); - parameters.put("output", output); - parameters.put("offcheck", offcheck); - logger.info("Validating " + filename + "\n"); - SBMLErrorLog sbmlErrorLog = SBMLValidator.checkConsistency(filename, parameters); - handleErrorLog(sbmlErrorLog, filename); - } else { logger.info(format(MESSAGES.getString("VAL_OFFLINE"), filename)); SBMLDocument doc = null; - try { - InputStream istream; - if (filename.endsWith(".gz")) { - istream = ZIPUtils.GUnzipStream(filename); - } else if (filename.endsWith(".zip")) { - istream = ZIPUtils.ZIPunCompressStream(filename); - } else { - istream = new FileInputStream(filename); - } - doc = SBMLReader.read(istream); - } catch (XMLStreamException | IOException e) { - e.printStackTrace(); + InputStream istream; + if (filename.endsWith(".gz")) { + istream = ZIPUtils.GUnzipStream(filename); + } else if (filename.endsWith(".zip")) { + istream = ZIPUtils.ZIPunCompressStream(filename); + } else { + istream = new FileInputStream(filename); } + doc = SBMLReader.read(istream); if (doc != null) { LoggingValidationContext context = new LoggingValidationContext(doc.getLevel(), doc.getVersion()); context.loadConstraints(SBMLDocument.class); @@ -85,6 +44,8 @@ public void validate(File outputFile, boolean online) { } else { logger.severe(format(MESSAGES.getString("VAL_OFFLINE_FAIL"), filename)); } + } catch (XMLStreamException | IOException e) { + throw new ModelValidatorException(e, outputFile); } } diff --git a/src/main/java/edu/ucsd/sbrg/ModelValidatorException.java b/src/main/java/edu/ucsd/sbrg/ModelValidatorException.java new file mode 100644 index 00000000..82128864 --- /dev/null +++ b/src/main/java/edu/ucsd/sbrg/ModelValidatorException.java @@ -0,0 +1,17 @@ +package edu.ucsd.sbrg; + +import java.io.File; + +public class ModelValidatorException extends Exception { + + private final File outputFile; + + public ModelValidatorException(Exception e, File outputFile) { + super(e); + this.outputFile = outputFile; + } + + public File outputFile() { + return outputFile; + } +} diff --git a/src/main/java/edu/ucsd/sbrg/annotation/AbstractAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/AbstractAnnotator.java index 7f098af1..52b40734 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/AbstractAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/AbstractAnnotator.java @@ -4,6 +4,7 @@ import edu.ucsd.sbrg.reporting.ProgressUpdate; import edu.ucsd.sbrg.reporting.ReportType; +import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @@ -19,11 +20,11 @@ public AbstractAnnotator(List observers) { this.observers = observers; } - public void annotate(List elementsToAnnotate) { + public void annotate(List elementsToAnnotate) throws SQLException { throw new UnsupportedOperationException(); } - abstract public void annotate(SBMLElement elementToAnnotate); + abstract public void annotate(SBMLElement elementToAnnotate) throws SQLException, AnnotationException; protected void statusReport(String text, Object element) { for (var o : observers) { @@ -31,6 +32,11 @@ protected void statusReport(String text, Object element) { } } + protected void diffReport(String elementType, Object element1, Object element2) { + for (var o : observers) { + o.update(new ProgressUpdate(elementType, List.of(element1, element2), ReportType.DATA)); + } + } public List getObservers() { return observers; } diff --git a/src/main/java/edu/ucsd/sbrg/annotation/AnnotationException.java b/src/main/java/edu/ucsd/sbrg/annotation/AnnotationException.java new file mode 100644 index 00000000..449b9b4a --- /dev/null +++ b/src/main/java/edu/ucsd/sbrg/annotation/AnnotationException.java @@ -0,0 +1,8 @@ +package edu.ucsd.sbrg.annotation; + +public class AnnotationException extends Exception{ + + public AnnotationException(String msg, Exception e) { + super(msg, e); + } +} diff --git a/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBReactionsAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBReactionsAnnotator.java index 239924b9..4360aa4b 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBReactionsAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBReactionsAnnotator.java @@ -6,6 +6,7 @@ import edu.ucsd.sbrg.db.bigg.BiGGId; import org.sbml.jsbml.Reaction; +import java.sql.SQLException; import java.util.*; import static edu.ucsd.sbrg.db.adb.AnnotateDBContract.Constants.BIGG_REACTION; @@ -17,15 +18,19 @@ public ADBReactionsAnnotator(AnnotateDB adb, ADBAnnotationParameters parameters) } @Override - public void annotate(List reactions) { - reactions.forEach(this::annotate); + public void annotate(List reactions) throws SQLException { + for (Reaction reaction : reactions) { + annotate(reaction); + } } @Override - public void annotate(Reaction reaction) { + public void annotate(Reaction reaction) throws SQLException { String id = reaction.getId(); Optional reactionId = BiGGId.createReactionId(id); - reactionId.ifPresent(biGGId -> addBQB_IS_AnnotationsFromADB(reaction.getAnnotation(), BIGG_REACTION, biGGId)); + if (reactionId.isPresent()) { + addBQB_IS_AnnotationsFromADB(reaction.getAnnotation(), BIGG_REACTION, reactionId.get()); + } if ((reaction.getCVTermCount() > 0) && !reaction.isSetMetaId()) { reaction.setMetaId(reaction.getId()); } diff --git a/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSBMLAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSBMLAnnotator.java index 292fb56d..2d7f6fe3 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSBMLAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSBMLAnnotator.java @@ -6,6 +6,8 @@ import org.sbml.jsbml.Model; import org.sbml.jsbml.SBMLDocument; +import java.sql.SQLException; + public class ADBSBMLAnnotator extends AbstractADBAnnotator { public ADBSBMLAnnotator(AnnotateDB adb, ADBAnnotationParameters parameters) { @@ -13,7 +15,7 @@ public ADBSBMLAnnotator(AnnotateDB adb, ADBAnnotationParameters parameters) { } @Override - public void annotate(SBMLDocument doc) { + public void annotate(SBMLDocument doc) throws SQLException { Model model = doc.getModel(); new ADBSpeciesAnnotator(adb, parameters).annotate(model.getListOfSpecies()); diff --git a/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSpeciesAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSpeciesAnnotator.java index 66717d4e..55576af8 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSpeciesAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/adb/ADBSpeciesAnnotator.java @@ -6,6 +6,7 @@ import edu.ucsd.sbrg.db.bigg.BiGGId; import org.sbml.jsbml.Species; +import java.sql.SQLException; import java.util.*; import static edu.ucsd.sbrg.db.adb.AnnotateDBContract.Constants.BIGG_METABOLITE; @@ -17,15 +18,19 @@ public ADBSpeciesAnnotator(AnnotateDB adb, ADBAnnotationParameters parameters) { } @Override - public void annotate(List species) { - species.forEach(this::annotate); + public void annotate(List species) throws SQLException { + for (Species s : species) { + annotate(s); + } } @Override - public void annotate(Species species) { + public void annotate(Species species) throws SQLException { String id = species.getId(); Optional metaboliteId = BiGGId.createMetaboliteId(id); - metaboliteId.ifPresent(biGGId -> addBQB_IS_AnnotationsFromADB(species.getAnnotation(), BIGG_METABOLITE, biGGId)); + if (metaboliteId.isPresent()) { + addBQB_IS_AnnotationsFromADB(species.getAnnotation(), BIGG_METABOLITE, metaboliteId.get()); + } if ((species.getCVTermCount() > 0) && !species.isSetMetaId()) { species.setMetaId(species.getId()); } diff --git a/src/main/java/edu/ucsd/sbrg/annotation/adb/AbstractADBAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/adb/AbstractADBAnnotator.java index 0f69186a..bdd78822 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/adb/AbstractADBAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/adb/AbstractADBAnnotator.java @@ -8,6 +8,7 @@ import org.sbml.jsbml.Annotation; import org.sbml.jsbml.CVTerm; +import java.sql.SQLException; import java.util.*; public abstract class AbstractADBAnnotator extends AbstractAnnotator { @@ -21,9 +22,9 @@ public AbstractADBAnnotator(AnnotateDB adb, ADBAnnotationParameters parameters) this.parameters = parameters; } - public abstract void annotate(SBMLElement element); + public abstract void annotate(SBMLElement element) throws SQLException; - protected void addBQB_IS_AnnotationsFromADB(Annotation annotation, String type, BiGGId biggId) { + protected void addBQB_IS_AnnotationsFromADB(Annotation annotation, String type, BiGGId biggId) throws SQLException { CVTerm cvTerm = annotation.getListOfCVTerms().stream() .filter(term -> term.getQualifier() == CVTerm.Qualifier.BQB_IS) .findFirst() diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/AbstractBiGGAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/AbstractBiGGAnnotator.java index c74e46b9..0cfacf35 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/AbstractBiGGAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/AbstractBiGGAnnotator.java @@ -13,10 +13,13 @@ import org.sbml.jsbml.Species; import org.sbml.jsbml.ext.fbc.GeneProduct; +import java.sql.SQLException; import java.util.List; import java.util.Optional; import java.util.stream.Stream; +import static java.util.stream.Stream.concat; + public abstract class AbstractBiGGAnnotator extends AbstractAnnotator { protected final BiGGDB bigg; @@ -48,7 +51,7 @@ public AbstractBiGGAnnotator(BiGGDB bigg, BiGGAnnotationParameters biGGAnnotatio * {@link BiGGDBContract.Constants#TYPE_GENE_PRODUCT}. * @return An {@link Optional } containing the BiGG ID if it could be successfully retrieved, otherwise {@link Optional#empty()}. */ - public Optional getBiGGIdFromResources(List resources, String type) { + public Optional getBiGGIdFromResources(List resources, String type) throws SQLException { var identifiersOrgUrisStream = resources.stream() .filter(registry::isValid) .map(IdentifiersOrgURI::new) @@ -61,11 +64,14 @@ public Optional getBiGGIdFromResources(List resources, String ty .map(Optional::get) .filter(registry::validRegistryUrlPrefix); - return Stream.concat(identifiersOrgUrisStream, resolvedIdentifiersOrgUrisStream) - .map(uri -> getBiggIdFromParts(uri, type)) - .filter(Optional::isPresent) - .map(Optional::get) - .findFirst(); + var uris = Stream.concat(identifiersOrgUrisStream, resolvedIdentifiersOrgUrisStream).toList(); + for (var uri : uris ) { + var biggId = getBiggIdFromParts(uri, type); + if (biggId.isPresent()) { + return biggId; + } + } + return Optional.empty(); } /** @@ -76,7 +82,7 @@ public Optional getBiGGIdFromResources(List resources, String ty * {@link BiGGDBContract.Constants} and include TYPE_SPECIES, TYPE_REACTION, and TYPE_GENE_PRODUCT. * @return An {@link Optional} containing the BiGG ID if found, otherwise {@link Optional#empty()}. */ - private Optional getBiggIdFromParts(RegistryURI uri, String type) { + private Optional getBiggIdFromParts(RegistryURI uri, String type) throws SQLException { if (bigg.isDataSource(uri.getPrefix())) { Optional id = bigg.getBiggIdFromSynonym(uri.getPrefix(), uri.getId(), type); if (id.isPresent()) { diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationException.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationException.java new file mode 100644 index 00000000..7c2da9ce --- /dev/null +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationException.java @@ -0,0 +1,17 @@ +package edu.ucsd.sbrg.annotation.bigg; + +import edu.ucsd.sbrg.annotation.AnnotationException; + +public class BiGGAnnotationException extends AnnotationException { + + private final Object data; + + public BiGGAnnotationException(String msg, Exception e, Object o) { + super(msg, e); + this.data = o; + } + + public Object data() { + return data; + } +} diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationUtils.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationUtils.java deleted file mode 100644 index c78bf758..00000000 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGAnnotationUtils.java +++ /dev/null @@ -1,6 +0,0 @@ -package edu.ucsd.sbrg.annotation.bigg; - -public class BiGGAnnotationUtils { - - -} diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCVTermAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCVTermAnnotator.java index bc6ef0f8..f6b9d796 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCVTermAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCVTermAnnotator.java @@ -7,6 +7,7 @@ import edu.ucsd.sbrg.reporting.ProgressObserver; import org.sbml.jsbml.*; +import java.sql.SQLException; import java.util.List; import java.util.Optional; @@ -33,7 +34,7 @@ public BiGGCVTermAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameters, Reg * * @return Optional containing the valid BiGG ID or empty if the ID is invalid. */ - protected abstract Optional findBiGGId(T element); + protected abstract Optional findBiGGId(T element) throws SQLException; // /** // * Adds annotations to an SBML node (either a Species or a Reaction) using a given BiGGId. diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotator.java index 11797ac4..97ac0450 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotator.java @@ -9,6 +9,7 @@ import edu.ucsd.sbrg.db.bigg.BiGGId; import edu.ucsd.sbrg.db.bigg.BiGGDB; +import java.sql.SQLException; import java.util.List; /** @@ -27,7 +28,8 @@ public BiGGCompartmentsAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameter super(bigg, parameters, registry, observers); } - public void annotate(List compartments) { + @Override + public void annotate(List compartments) throws SQLException { for (Compartment compartment : compartments) { statusReport("Annotating Compartments (2/5) ", compartment); annotate(compartment); @@ -39,12 +41,13 @@ public void annotate(List compartments) { * it updates the name based on the BiGG database. This method only processes compartments that are recognized * within the BiGG Knowledgebase. */ - public void annotate(Compartment compartment) { + @Override + public void annotate(Compartment compartment) throws SQLException { BiGGId biggId = new BiGGId(compartment.getId()); if (bigg.isCompartment(biggId.getAbbreviation())) { compartment.addCVTerm( new CVTerm(CVTerm.Qualifier.BQB_IS, - new IdentifiersOrgURI("bigg.compartment", biggId).getURI())); + new IdentifiersOrgURI("bigg.compartment", biggId).getURI())); compartment.setSBOTerm(SBO.getCompartment()); // physical compartment if (!compartment.isSetName() || compartment.getName().equals("default")) { bigg.getCompartmentName(biggId).ifPresent(compartment::setName); diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGDocumentNotesProcessor.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGDocumentNotesProcessor.java index 28ddf9da..5cd56344 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGDocumentNotesProcessor.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGDocumentNotesProcessor.java @@ -8,6 +8,7 @@ import javax.xml.stream.XMLStreamException; import java.io.*; +import java.sql.SQLException; import java.util.*; import java.util.logging.Logger; @@ -27,14 +28,14 @@ public BiGGDocumentNotesProcessor(BiGGDB bigg, BiGGAnnotationParameters paramete } - public void processNotes(SBMLDocument doc) { + public void processNotes(SBMLDocument doc) throws BiGGAnnotationException, SQLException { var model = doc.getModel(); - // Process replacements for placeholders in the model notes - Map replacements = processReplacements(model); try { + // Process replacements for placeholders in the model notes + Map replacements = processReplacements(model); appendNotes(doc, replacements); - } catch (IOException | XMLStreamException exc) { - logger.warning(MESSAGES.getString("FAILED_WRITE_NOTES")); + } catch (IOException | XMLStreamException e) { + throw new BiGGAnnotationException(MESSAGES.getString("FAILED_WRITE_NOTES"), e, doc); } } @@ -47,7 +48,7 @@ public void processNotes(SBMLDocument doc) { * * @return A map of placeholder strings and their corresponding replacement values. */ - private Map processReplacements(Model model) { + private Map processReplacements(Model model) throws SQLException { // Retrieve the model ID String id = model.getId(); // Attempt to retrieve the organism name associated with the model ID; use an empty string if not available diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotator.java index c4a358fa..3841e592 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotator.java @@ -12,6 +12,7 @@ import org.sbml.jsbml.Species; import org.sbml.jsbml.ext.fbc.GeneProduct; +import java.sql.SQLException; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -45,7 +46,7 @@ public BiGGModelAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameters, Regi * 3. Sets the model's MetaId to its ID if MetaId is not already set and the model has at least one CVTerm. */ @Override - public void annotate(Model model) { + public void annotate(Model model) throws SQLException { // Retrieve the model ID String id = model.getId(); // Attempt to retrieve the organism name associated with the model ID; use an empty string if not available @@ -72,7 +73,7 @@ public void annotate(Model model) { } - private void addTaxonomyAnnotation(Model model, String modelId) { + private void addTaxonomyAnnotation(Model model, String modelId) throws SQLException { // Attempt to fetch and add a taxonomy annotation using the model's ID bigg.getTaxonId(modelId).ifPresent( taxonId -> model.addCVTerm( diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGPublicationsAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGPublicationsAnnotator.java index 08de7d87..b0134cc6 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGPublicationsAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGPublicationsAnnotator.java @@ -9,6 +9,7 @@ import org.sbml.jsbml.CVTerm; import org.sbml.jsbml.Model; +import java.sql.SQLException; import java.util.List; public class BiGGPublicationsAnnotator extends AbstractBiGGAnnotator { @@ -19,7 +20,7 @@ public BiGGPublicationsAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameter } @Override - public void annotate(Model model) { + public void annotate(Model model) throws SQLException { List publications = bigg.getPublications(model.getId()); statusReport("Annotating Publications (1/5) ", model); diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotator.java index 1e9d02db..df0cd756 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotator.java @@ -19,6 +19,7 @@ import org.sbml.jsbml.ext.groups.GroupsConstants; import org.sbml.jsbml.ext.groups.GroupsModelPlugin; +import java.sql.SQLException; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; @@ -56,7 +57,7 @@ public BiGGReactionsAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameters, * and invokes the annotation for each reaction. */ @Override - public void annotate(List reactions) { + public void annotate(List reactions) throws SQLException { for (Reaction reaction : reactions) { annotate(reaction); } @@ -69,16 +70,17 @@ public void annotate(List reactions) { * annotation and parsing processes. */ @Override - public void annotate(Reaction reaction) { + public void annotate(Reaction reaction) throws SQLException { statusReport("Annotating Reactions (4/5) ", reaction); // Attempt to retrieve a BiGG ID for the reaction, either directly from the reaction ID or through associated annotations - findBiGGId(reaction).ifPresent(biggId -> { - setName(reaction, biggId); // Set the reaction's name based on the BiGG ID - setSBOTerm(reaction, biggId); // Assign the appropriate SBO term based on the BiGG ID - addAnnotations(reaction, biggId); // Add additional annotations related to the BiGG ID - parseGeneReactionRules(reaction, biggId); // Parse and process gene reaction rules associated with the BiGG ID - parseSubsystems(reaction, biggId); // Convert subsystem information into corresponding groups based on the BiGG ID - }); + var biggId = findBiGGId(reaction); + if (biggId.isPresent()) { + setName(reaction, biggId.get()); // Set the reaction's name based on the BiGG ID + setSBOTerm(reaction, biggId.get()); // Assign the appropriate SBO term based on the BiGG ID + addAnnotations(reaction, biggId.get()); // Add additional annotations related to the BiGG ID + parseGeneReactionRules(reaction, biggId.get()); // Parse and process gene reaction rules associated with the BiGG ID + parseSubsystems(reaction, biggId.get()); // Convert subsystem information into corresponding groups based on the BiGG ID + } } /** @@ -92,7 +94,7 @@ public void annotate(Reaction reaction) { * @return An {@link Optional} containing the BiGG ID if found or created successfully, otherwise {@link Optional#empty()} */ @Override - public Optional findBiGGId(Reaction reaction) { + public Optional findBiGGId(Reaction reaction) throws SQLException { String id = reaction.getId(); // Check if the reaction ID matches the expected BiGG ID format and exists in the database boolean isBiGGid = bigg.isReaction(id); @@ -155,7 +157,7 @@ private boolean matchingCompartments(Reaction reaction, BiGGDB.ForeignReaction f * * @param biggId The BiGGId object containing the abbreviation used to fetch and potentially update the reaction's name. */ - public void setName(Reaction reaction, BiGGId biggId) { + public void setName(Reaction reaction, BiGGId biggId) throws SQLException { String abbreviation = biggId.getAbbreviation(); bigg.getReactionName(abbreviation) .filter(name -> !name.equals(reaction.getName())) @@ -172,7 +174,7 @@ public void setName(Reaction reaction, BiGGId biggId) { * * @param biggId The BiGGId object containing the abbreviation used to check if the reaction is a pseudoreaction. */ - public void setSBOTerm(Reaction reaction, BiGGId biggId) { + public void setSBOTerm(Reaction reaction, BiGGId biggId) throws SQLException { String abbreviation = biggId.getAbbreviation(); if (!reaction.isSetSBOTerm()) { if (bigg.isPseudoreaction(abbreviation)) { @@ -183,7 +185,7 @@ public void setSBOTerm(Reaction reaction, BiGGId biggId) { } } - void addAnnotations(Reaction node, BiGGId biggId) { + void addAnnotations(Reaction node, BiGGId biggId) throws SQLException { // TODO: ??? CVTerm cvTerm = null; for (CVTerm term : node.getAnnotation().getListOfCVTerms()) { @@ -239,7 +241,7 @@ void addAnnotations(Reaction node, BiGGId biggId) { * * @param biggId The BiGG database identifier for the reaction, used to fetch and parse gene reaction rules. */ - public void parseGeneReactionRules(Reaction reaction, BiGGId biggId) { + public void parseGeneReactionRules(Reaction reaction, BiGGId biggId) throws SQLException { String abbreviation = biggId.getAbbreviation(); List geneReactionRules = bigg.getGeneReactionRule(abbreviation, reaction.getModel().getId()); for (String geneReactionRule : geneReactionRules) { @@ -259,7 +261,7 @@ public void parseGeneReactionRules(Reaction reaction, BiGGId biggId) { * * @param biggId the {@link BiGGId} associated with the reaction, used to fetch subsystem information */ - private void parseSubsystems(Reaction reaction, BiGGId biggId) { + private void parseSubsystems(Reaction reaction, BiGGId biggId) throws SQLException { Model model = reaction.getModel(); boolean isBiGGModel = bigg.isModel(model.getId()); List subsystems; diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotator.java index cdd9f255..12cb7753 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotator.java @@ -1,7 +1,9 @@ package edu.ucsd.sbrg.annotation.bigg; +import java.sql.SQLException; import java.util.List; +import edu.ucsd.sbrg.annotation.AnnotationException; import edu.ucsd.sbrg.parameters.BiGGAnnotationParameters; import edu.ucsd.sbrg.parameters.SBOParameters; import edu.ucsd.sbrg.annotation.AnnotationsSorter; @@ -44,7 +46,7 @@ public BiGGSBMLAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameters, SBOPa * @param doc The SBMLDocument that contains the model to be annotated. */ @Override - public void annotate(SBMLDocument doc) { + public void annotate(SBMLDocument doc) throws SQLException, AnnotationException { // TODO: these sanity checks need to be improved Model model = doc.getModel(); String modelId = model.getId(); diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotator.java index c7e621c6..578087ad 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotator.java @@ -15,6 +15,7 @@ import org.sbml.jsbml.ext.fbc.FBCConstants; import org.sbml.jsbml.ext.fbc.FBCSpeciesPlugin; +import java.sql.SQLException; import java.util.*; import java.util.logging.Logger; import java.util.stream.Collectors; @@ -49,7 +50,8 @@ protected BiGGSpeciesAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameters, * Delegates annotation processing for all chemical species contained in the {@link Model}. * This method iterates over each species in the model and applies specific annotations. */ - public void annotate(List species) { + @Override + public void annotate(List species) throws SQLException { for (Species s : species) { statusReport("Annotating Species (3/5) ", s); annotate(s); @@ -66,14 +68,15 @@ public void annotate(List species) { * The BiGGId used for these operations is either derived from the species' URI list or directly from its ID if available. */ @Override - public void annotate(Species species) { + public void annotate(Species species) throws SQLException { // Retrieve the BiGGId for the species, either from its URI list or its direct ID - findBiGGId(species).ifPresent(biggId -> { - setName(species, biggId); // Set the species name based on the BiGGId - setSBOTerm(species, biggId); // Assign the appropriate SBO term - addAnnotations(species, biggId); // Add database cross-references and other annotations - FBCSetFormulaCharge(species, biggId); // Set the chemical formula and charge - }); + Optional biGGId = findBiGGId(species); + if (biGGId.isPresent()) { + setName(species, biGGId.get()); // Set the species name based on the BiGGId + setSBOTerm(species, biGGId.get()); // Assign the appropriate SBO term + addAnnotations(species, biGGId.get()); // Add database cross-references and other annotations + FBCSetFormulaCharge(species, biGGId.get()); // Set the chemical formula and charge + }; } @@ -85,25 +88,24 @@ public void annotate(Species species) { * @return An {@link Optional} containing the BiGGId if a valid one is found or created, otherwise {@link Optional#empty()} */ @Override - public Optional findBiGGId(Species species) { + public Optional findBiGGId(Species species) throws SQLException { // Attempt to create a BiGGId from the species ID Optional metaboliteId = BiGGId.createMetaboliteId(species.getId()); // Check if the created BiGGId is valid, if not, try to find a BiGGId from annotations - Optional id = metaboliteId.flatMap(biggId -> { - boolean isBiGGid = bigg.isMetabolite(biggId.getAbbreviation()); - List resources = new ArrayList<>(); - if (!isBiGGid) { + if (metaboliteId.isPresent()) { + boolean isBiGGid = bigg.isMetabolite(metaboliteId.get().getAbbreviation()); + if (!isBiGGid) { // Collect all resources from CVTerms that qualify as BQB_IS - resources = species.getAnnotation().getListOfCVTerms().stream() - .filter(cvTerm -> cvTerm.getQualifier() == Qualifier.BQB_IS) - .flatMap(term -> term.getResources().stream()) - .collect(Collectors.toList()); + // Attempt to retrieve a BiGGId from the collected resources + return getBiGGIdFromResources(species.getAnnotation().getListOfCVTerms().stream() + .filter(cvTerm -> cvTerm.getQualifier() == Qualifier.BQB_IS) + .flatMap(term -> term.getResources().stream()) + .toList(), TYPE_SPECIES); } - // Attempt to retrieve a BiGGId from the collected resources - return getBiGGIdFromResources(resources, TYPE_SPECIES); - }); - // Return the found BiGGId or the originally created one if no new ID was found - return id.map(BiGGId::toBiGGId).map(BiGGId::createMetaboliteId).orElse(metaboliteId); + // Return the found BiGGId or the originally created one if no new ID was found + return metaboliteId.map(BiGGId::toBiGGId).map(BiGGId::createMetaboliteId).orElse(metaboliteId); + } + return Optional.empty(); } @@ -114,7 +116,7 @@ public Optional findBiGGId(Species species) { * * @param biggId The {@link BiGGId} associated with the species, used to fetch the component name from the BiGG database. */ - public void setName(Species species, BiGGId biggId) { + public void setName(Species species, BiGGId biggId) throws SQLException { if (!species.isSetName() || species.getName().equals(format("{0}_{1}", biggId.getAbbreviation(), biggId.getCompartmentCode()))) { bigg.getComponentName(biggId).map(PolishingUtils::polishName).ifPresent(species::setName); @@ -130,7 +132,7 @@ public void setName(Species species, BiGGId biggId) { * * @param biggId The {@link BiGGId} associated with the species, used to determine the component type from the BiGG database. */ - private void setSBOTerm(Species species, BiGGId biggId) { + private void setSBOTerm(Species species, BiGGId biggId) throws SQLException { bigg.getComponentType(biggId).ifPresentOrElse(type -> { switch (type) { case "metabolite": @@ -153,7 +155,7 @@ private void setSBOTerm(Species species, BiGGId biggId) { } - void addAnnotations(Species species, BiGGId biggId) throws IllegalArgumentException { + void addAnnotations(Species species, BiGGId biggId) throws IllegalArgumentException, SQLException { // TODO: ??? CVTerm cvTerm = null; @@ -210,7 +212,7 @@ void addAnnotations(Species species, BiGGId biggId) throws IllegalArgumentExcept * @param biggId: {@link BiGGId} from species id */ @SuppressWarnings("deprecation") - private void FBCSetFormulaCharge(Species species, BiGGId biggId) { + private void FBCSetFormulaCharge(Species species, BiGGId biggId) throws SQLException { boolean isBiGGModel = species.getModel() !=null && bigg.isModel(species.getModel().getId()); String compartmentCode = biggId.getCompartmentCode(); diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGFBCAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGFBCAnnotator.java index 8d160ceb..ee688780 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGFBCAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGFBCAnnotator.java @@ -9,6 +9,7 @@ import org.sbml.jsbml.ext.fbc.FBCConstants; import org.sbml.jsbml.ext.fbc.FBCModelPlugin; +import java.sql.SQLException; import java.util.List; public class BiGGFBCAnnotator extends AbstractBiGGAnnotator { @@ -18,7 +19,7 @@ public BiGGFBCAnnotator(BiGGDB bigg, BiGGAnnotationParameters parameters, Regist } @Override - public void annotate(Model model) { + public void annotate(Model model) throws SQLException { // // Calculate the change in the number of gene products to update the progress bar accordingly // int changed = fbcModelPlugin.getNumGeneProducts() - initialGeneProducts; // if (changed > 0) { diff --git a/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGGeneProductAnnotator.java b/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGGeneProductAnnotator.java index ca88e69f..69931f3d 100644 --- a/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGGeneProductAnnotator.java +++ b/src/main/java/edu/ucsd/sbrg/annotation/bigg/fbc/BiGGGeneProductAnnotator.java @@ -12,6 +12,7 @@ import org.sbml.jsbml.CVTerm.Qualifier; import org.sbml.jsbml.ext.fbc.GeneProduct; +import java.sql.SQLException; import java.util.List; import java.util.Optional; import java.util.ResourceBundle; @@ -50,7 +51,7 @@ public BiGGGeneProductAnnotator(BiGGGeneProductReferencesAnnotator gprAnnotator, * the number of gene products being annotated. */ @Override - public void annotate(List geneProducts) { + public void annotate(List geneProducts) throws SQLException { // Iterate over each gene product and annotate it for (GeneProduct geneProduct : geneProducts) { statusReport("Annotating Gene Products (5/5) ", geneProduct); @@ -67,20 +68,19 @@ public void annotate(List geneProducts) { * and sets the gene product's metaId if it has any CV terms. Finally, it sets the gene product's label name. */ @Override - public void annotate(GeneProduct geneProduct) { + public void annotate(GeneProduct geneProduct) throws SQLException { Optional biggId = findBiGGId(geneProduct); Optional label = biggId.map(id -> getLabel(geneProduct, id)); if (label.isEmpty()) { return; } + gprAnnotator.update(geneProduct); - biggId.ifPresent(id -> { - addAnnotations(geneProduct, id); - if (geneProduct.getCVTermCount() > 0) { - geneProduct.setMetaId(id.toBiGGId()); - } - }); + addAnnotations(geneProduct, biggId.get()); + if (geneProduct.getCVTermCount() > 0) { + geneProduct.setMetaId(biggId.get().toBiGGId()); + } setGPLabelName(geneProduct, label.get()); } @@ -96,7 +96,7 @@ public void annotate(GeneProduct geneProduct) { * @return An {@link Optional} containing the validated or retrieved BiGG ID, or an empty Optional if no valid ID is found. */ @Override - public Optional findBiGGId(GeneProduct geneProduct) { + public Optional findBiGGId(GeneProduct geneProduct) throws SQLException { String id = geneProduct.getId(); boolean isBiGGid = id.matches(BIGG_GENE_ID_PATTERN); if (!isBiGGid) { @@ -145,7 +145,7 @@ public String getLabel(GeneProduct geneProduct, BiGGId biggId) { * @param label The label to set or use for fetching the gene name. This label should correspond to a {@link BiGGId} * or be derived from {@link GeneProduct#getId()}. */ - public void setGPLabelName(GeneProduct geneProduct, String label) { + public void setGPLabelName(GeneProduct geneProduct, String label) throws SQLException { // Check if the current label is "None" and update it if so if (geneProduct.getLabel().equalsIgnoreCase("None")) { geneProduct.setLabel(label); @@ -175,7 +175,7 @@ public void setGPLabelName(GeneProduct geneProduct, String label) { * * @param biggId The {@link BiGGId} associated with the gene product, typically derived from a species ID. */ - public void addAnnotations(GeneProduct geneProduct, BiGGId biggId) { + public void addAnnotations(GeneProduct geneProduct, BiGGId biggId) throws SQLException { CVTerm termIs = new CVTerm(Qualifier.BQB_IS); CVTerm termEncodedBy = new CVTerm(Qualifier.BQB_IS_ENCODED_BY); // Retrieve gene IDs from BiGG database and categorize them based on their prefix diff --git a/src/main/java/edu/ucsd/sbrg/db/adb/AnnotateDB.java b/src/main/java/edu/ucsd/sbrg/db/adb/AnnotateDB.java index ddf34d51..4824f8e3 100644 --- a/src/main/java/edu/ucsd/sbrg/db/adb/AnnotateDB.java +++ b/src/main/java/edu/ucsd/sbrg/db/adb/AnnotateDB.java @@ -3,7 +3,10 @@ import de.zbit.util.Utils; import de.zbit.util.prefs.SBProperties; import edu.ucsd.sbrg.db.PostgresConnectionPool; +import edu.ucsd.sbrg.db.bigg.BiGGDB; import edu.ucsd.sbrg.parameters.DBParameters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.PreparedStatement; @@ -11,7 +14,6 @@ import java.sql.SQLException; import java.util.Set; import java.util.TreeSet; -import java.util.logging.Logger; import static edu.ucsd.sbrg.db.adb.AnnotateDBContract.Constants.BIGG_METABOLITE; import static edu.ucsd.sbrg.db.adb.AnnotateDBContract.Constants.BIGG_REACTION; @@ -31,7 +33,7 @@ */ public class AnnotateDB { - private static final Logger logger = Logger.getLogger(AnnotateDB.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(AnnotateDB.class); private static PostgresConnectionPool connectionPool; public AnnotateDB (DBParameters parameters) { @@ -60,6 +62,7 @@ public AnnotateDB(String host, Integer port, String user, String passwd, String public static void init(String host, Integer port, String user, String passwd, String dbName) { if (null == connectionPool) { + logger.debug("Initialize AnnotateDB"); connectionPool = new PostgresConnectionPool(host, port, user, passwd, dbName); Runtime.getRuntime().addShutdownHook(new Thread(connectionPool::close)); @@ -77,7 +80,7 @@ public static void init(String host, Integer port, String user, String passwd, S * @return A sorted set of URLs that are annotations for the given BiGG ID. If the type is neither metabolite * nor reaction, or if an SQL exception occurs, an empty set is returned. */ - public Set getAnnotations(String type, String biggId) { + public Set getAnnotations(String type, String biggId) throws SQLException { TreeSet annotations = new TreeSet<>(); // Check if the type is valid for querying annotations if (!type.equals(BIGG_METABOLITE) && !type.equals(BIGG_REACTION)) { @@ -110,8 +113,6 @@ public Set getAnnotations(String type, String biggId) { annotations.add(uri); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return annotations; } diff --git a/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGDB.java b/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGDB.java index 14ecd21c..9ea9b03b 100644 --- a/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGDB.java +++ b/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGDB.java @@ -18,13 +18,15 @@ import de.zbit.util.Utils; import edu.ucsd.sbrg.parameters.DBParameters; import edu.ucsd.sbrg.db.PostgresConnectionPool; +import edu.ucsd.sbrg.polishing.SBMLPolisher; import edu.ucsd.sbrg.resolver.RegistryURI; import edu.ucsd.sbrg.resolver.identifiersorg.IdentifiersOrgURI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.sql.Date; import java.sql.*; import java.util.*; -import java.util.logging.Logger; import java.util.stream.Collectors; import static edu.ucsd.sbrg.db.bigg.BiGGDBContract.Constants.Column.*; @@ -40,7 +42,7 @@ @SuppressWarnings("ALL") public class BiGGDB { - private static final Logger logger = Logger.getLogger(BiGGDB.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(BiGGDB.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private static PostgresConnectionPool connectionPool; @@ -76,7 +78,9 @@ public BiGGDB(String host, Integer port, String user, String passwd, String dbNa } public static void init(String host, Integer port, String user, String passwd, String dbName) { + if (null == connectionPool) { + logger.debug("Initialize BiGG DB"); connectionPool = new PostgresConnectionPool(host, port, user, passwd, dbName); Runtime.getRuntime().addShutdownHook(new Thread(connectionPool::close)); @@ -92,7 +96,7 @@ public static void init(String host, Integer port, String user, String passwd, S * * @return {@link Optional} The date of the last database update, or an empty {@link Optional} if not available. */ - public Optional getBiGGVersion() { + public Optional getBiGGVersion() throws SQLException { Optional date = Optional.empty(); String query = "SELECT " + DATE_TIME + " FROM " + DATABASE_VERSION; try (Connection connection = connectionPool.getConnection(); @@ -101,8 +105,6 @@ public Optional getBiGGVersion() { if (resultSet.next()) { date = Optional.of(resultSet.getDate(1)); } - } catch (SQLException exc) { - logger.finest(format("{0}: {1}", exc.getClass().getName(), Utils.getMessage(exc))); } return date; } @@ -117,7 +119,7 @@ public Optional getBiGGVersion() { * @param reactionBiGGid The BiGG ID of the reaction. * @return A List of subsystem names as strings. Returns an empty list if no subsystems are found or if an error occurs. */ - public List getSubsystems(String modelBiGGid, String reactionBiGGid) { + public List getSubsystems(String modelBiGGid, String reactionBiGGid) throws SQLException { String query = "SELECT DISTINCT mr." + SUBSYSTEM + " FROM " + REACTION + " r, " + MODEL + " m, " + MODEL_REACTION + " mr WHERE m." + BIGG_ID + " = ? AND r." + BIGG_ID + " = ? AND m." + ID + " = mr." + MODEL_ID + " AND r." + ID + " = mr." + REACTION_ID + " AND LENGTH(mr." + SUBSYSTEM + ") > 0"; @@ -131,8 +133,6 @@ public List getSubsystems(String modelBiGGid, String reactionBiGGid) { list.add(resultSet.getString(1)); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return list; } @@ -146,7 +146,7 @@ public List getSubsystems(String modelBiGGid, String reactionBiGGid) { * @param reactionBiGGid The BiGG ID of the reaction for which subsystems are to be retrieved. * @return A List of subsystem names as strings. Returns an empty list if no subsystems are found or if an error occurs. */ - public List getSubsystemsForReaction(String reactionBiGGid) { + public List getSubsystemsForReaction(String reactionBiGGid) throws SQLException { String query = "SELECT DISTINCT mr." + SUBSYSTEM + " FROM " + REACTION + " r, " + MODEL_REACTION + " mr WHERE r." + BIGG_ID + " = ? AND r." + ID + " = mr." + REACTION_ID + " AND LENGTH(mr." + SUBSYSTEM + ") > 0"; List list = new LinkedList<>(); @@ -158,8 +158,6 @@ public List getSubsystemsForReaction(String reactionBiGGid) { list.add(resultSet.getString(1)); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return list; } @@ -176,7 +174,7 @@ public List getSubsystemsForReaction(String reactionBiGGid) { * @return An {@link Optional} containing the chemical formula if exactly one unique formula is found, * otherwise an empty {@link Optional} if none or multiple formulas are found. */ - public Optional getChemicalFormulaByCompartment(String componentId, String compartmentId) { + public Optional getChemicalFormulaByCompartment(String componentId, String compartmentId) throws SQLException { String query = "SELECT DISTINCT mcc." + FORMULA + " FROM " + MCC + " mcc, " + COMPARTMENTALIZED_COMPONENT + " cc, " + COMPONENT + " c, " + COMPARTMENT + " co WHERE c." + BIGG_ID + " = ? AND c." + ID + " = cc." + COMPONENT_ID + " AND co." + BIGG_ID + " = ? AND co." + ID + " = cc." + COMPARTMENT_ID + " and cc." + ID + " = mcc." @@ -203,7 +201,7 @@ public Optional getChemicalFormulaByCompartment(String componentId, Stri * @param compartmentOrModelId The BiGG ID of either the compartment or the model associated with the component. * @return A set of unique chemical formulas as strings. If no valid formulas are found, returns an empty set. */ - private Set runFormulaQuery(String query, String componentId, String compartmentOrModelId) { + private Set runFormulaQuery(String query, String componentId, String compartmentOrModelId) throws SQLException { Set results = new HashSet<>(); try (Connection connection = connectionPool.getConnection()) { try (PreparedStatement pStatement = connection.prepareStatement(query)) { @@ -215,8 +213,6 @@ private Set runFormulaQuery(String query, String componentId, String com } } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return results.stream().filter(formula -> formula != null && !formula.isEmpty()).collect(Collectors.toSet()); } @@ -232,7 +228,7 @@ private Set runFormulaQuery(String query, String componentId, String com * @param modelId The BiGG ID of the model in which the component is present. * @return An {@link Optional} containing the chemical formula if exactly one is found, otherwise empty. */ - public Optional getChemicalFormula(String componentId, String modelId) { + public Optional getChemicalFormula(String componentId, String modelId) throws SQLException { String query = "SELECT DISTINCT mcc." + FORMULA + "\n FROM " + COMPONENT + " c,\n" + COMPARTMENTALIZED_COMPONENT + " cc,\n" + MODEL + " m,\n" + MCC + " mcc\n WHERE c." + ID + " = cc." + COMPONENT_ID + " AND\n cc." + ID + " = mcc." + COMPARTMENTALIZED_COMPONENT_ID + " AND\n c." + BIGG_ID + " = ? AND\n m." + BIGG_ID + " = ? AND\n m." @@ -257,7 +253,7 @@ public Optional getChemicalFormula(String componentId, String modelId) { * @param biggId The BiGGId object containing the abbreviation of the compartment. * @return An {@link Optional} containing the name of the compartment if found, otherwise empty. */ - public Optional getCompartmentName(BiGGId biggId) { + public Optional getCompartmentName(BiGGId biggId) throws SQLException { String query = "SELECT " + NAME + " FROM " + COMPARTMENT + " WHERE " + BIGG_ID + " = ? AND " + NAME + " <> ''"; return singleParamStatement(query, biggId.getAbbreviation()); } @@ -272,7 +268,7 @@ public Optional getCompartmentName(BiGGId biggId) { * @param param The parameter value to be used in the SQL query. * @return An {@link Optional} containing the result if exactly one result is found, otherwise empty. */ - public Optional singleParamStatement(String query, String param) { + public Optional singleParamStatement(String query, String param) throws SQLException { Set results = new HashSet<>(); try (Connection connection = connectionPool.getConnection(); PreparedStatement pStatement = connection.prepareStatement(query)){ @@ -282,15 +278,13 @@ public Optional singleParamStatement(String query, String param) { results.add(resultSet.getString(1)); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } results = results.stream().filter(result -> result != null && !result.isEmpty()).collect(Collectors.toSet()); if (results.size() == 1) { return Optional.of(results.iterator().next()); } else { if (results.size() > 1) { - logger.severe(format(MESSAGES.getString("QUERY_MULTIPLE_RESULTS"), param, query)); + logger.info(format(MESSAGES.getString("QUERY_MULTIPLE_RESULTS"), param, query)); } return Optional.empty(); } @@ -305,7 +299,7 @@ public Optional singleParamStatement(String query, String param) { * @param biggId The BiGGId object containing the abbreviation of the component. * @return An {@link Optional} containing the name of the component if found, otherwise empty. */ - public Optional getComponentName(BiGGId biggId) { + public Optional getComponentName(BiGGId biggId) throws SQLException { String query = "SELECT " + NAME + " FROM " + COMPONENT + " WHERE " + BIGG_ID + " = ? AND " + NAME + " <> ''"; return singleParamStatement(query, biggId.getAbbreviation()); } @@ -318,7 +312,7 @@ public Optional getComponentName(BiGGId biggId) { * @param biggId The BiGGId object containing the abbreviation of the component. * @return An {@link Optional} containing the type of the component if found, otherwise empty. */ - public Optional getComponentType(BiGGId biggId) { + public Optional getComponentType(BiGGId biggId) throws SQLException { String query = "SELECT " + TYPE + " FROM " + COMPONENT + " WHERE " + BIGG_ID + " = ? AND " + NAME + " <> ''"; return singleParamStatement(query, biggId.getAbbreviation()); } @@ -332,7 +326,7 @@ public Optional getComponentType(BiGGId biggId) { * @param label The label used to query gene identifiers. * @return A TreeSet containing unique, sorted MIRIAM-compliant gene identifiers. */ - public TreeSet getGeneIds(String label) { + public TreeSet getGeneIds(String label) throws SQLException { TreeSet results = new TreeSet<>(); String query = "SELECT " + URL_PREFIX + ", s." + SYNONYM + "\n" + "FROM " + DATA_SOURCE + " d, " + SYNONYM + " s, " + GENOME_REGION + " gr\n" + "WHERE d." + ID + " = s." + DATA_SOURCE_ID + " AND\n s." + OME_ID + " = gr." + ID @@ -349,16 +343,14 @@ public TreeSet getGeneIds(String label) { if (prefix != null && id != null) { results.add(new IdentifiersOrgURI(prefix, id)); } else if (prefix == null) { - logger.fine(MESSAGES.getString("COLLECTION_NULL_GENE")); + logger.info(MESSAGES.getString("COLLECTION_NULL_GENE")); continue; } else { - logger.warning(format(MESSAGES.getString("IDENTIFIER_NULL_GENE"), prefix)); + logger.info(format(MESSAGES.getString("IDENTIFIER_NULL_GENE"), prefix)); continue; } } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return results; } @@ -374,7 +366,7 @@ public TreeSet getGeneIds(String label) { * @param label The label used to query the gene name, typically a BIGG ID. * @return An {@link Optional} containing the gene name if found, otherwise an empty {@link Optional}. */ - public Optional getGeneName(String label) { + public Optional getGeneName(String label) throws SQLException { String query = "SELECT s." + SYNONYM + "\n" + "FROM " + DATA_SOURCE + " d, " + SYNONYM + " s, " + GENOME_REGION + " gr\n" + "WHERE d." + ID + " = s." + DATA_SOURCE_ID + " AND\n s." + OME_ID + " = gr." + ID + " AND\n gr." + BIGG_ID + " = ? AND\n d." + BIGG_ID + " LIKE " + REFSEQ_NAME + " AND s." + SYNONYM_COL + " <> ''"; @@ -392,7 +384,7 @@ public Optional getGeneName(String label) { * @param modelId The ID of the model associated with the reaction. * @return A list of formatted gene reaction rules as strings. */ - public List getGeneReactionRule(String reactionId, String modelId) { + public List getGeneReactionRule(String reactionId, String modelId) throws SQLException { return getReactionRules("SELECT REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(mr." + GENE_REACTION_RULE + ", 'or', '||'), 'and', '&&'), '.'), '.', '__SBML_DOT__'), '_AT', '__SBML_DOT__') AS " + GENE_REACTION_RULE + " FROM " + MODEL_REACTION + " mr, " + REACTION + " r, " + MODEL + " m WHERE r." + ID + " = mr." + REACTION_ID @@ -412,7 +404,7 @@ public List getGeneReactionRule(String reactionId, String modelId) { * @param modelId The ID of the model to be used as the second parameter in the SQL query. * @return A list of strings where each string is a gene reaction rule retrieved based on the given IDs. */ - public List getReactionRules(String query, String reactionId, String modelId) { + public List getReactionRules(String query, String reactionId, String modelId) throws SQLException { List results = new ArrayList<>(); try (Connection connection = connectionPool.getConnection(); PreparedStatement pStatement = connection.prepareStatement(query)){ @@ -423,8 +415,6 @@ public List getReactionRules(String query, String reactionId, String mod results.add(resultSet.getString(1)); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return results; } @@ -438,7 +428,7 @@ public List getReactionRules(String query, String reactionId, String mod * @param abbreviation The abbreviation of the model for which the organism is to be retrieved. * @return An Optional containing the organism name if found, otherwise an empty Optional. */ - public Optional getOrganism(String abbreviation) { + public Optional getOrganism(String abbreviation) throws SQLException { String query = "SELECT g." + ORGANISM + " FROM " + GENOME + " g, " + MODEL + " m WHERE m." + GENOME_ID + " = g." + ID + " AND m." + BIGG_ID + " = ?"; return singleParamStatement(query, abbreviation); @@ -453,7 +443,7 @@ public Optional getOrganism(String abbreviation) { * @param abbreviation The abbreviation of the model for which the publications are to be retrieved. * @return A list of pairs where each pair consists of a publication type and its corresponding ID. */ - public List getPublications(String abbreviation) { + public List getPublications(String abbreviation) throws SQLException { List results = new ArrayList<>(); String query = "SELECT p." + REFERENCE_TYPE + ", p." + REFERENCE_ID + " FROM " + PUBLICATION + " p, " + PUBLICATION_MODEL + " pm, " + MODEL + " m WHERE p." + ID + " = pm." + PUBLICATION_ID + " AND pm." + MODEL_ID @@ -467,8 +457,6 @@ public List getPublications(String abbreviation) { results.add(new Publication(key.equals("pmid") ? "pubmed" : key, resultSet.getString(2))); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return results; } @@ -482,7 +470,7 @@ public List getPublications(String abbreviation) { * @param abbreviation The abbreviation of the reaction for which the name is to be retrieved. * @return An Optional containing the reaction name if found and not empty, otherwise an empty Optional. */ - public Optional getReactionName(String abbreviation) { + public Optional getReactionName(String abbreviation) throws SQLException { String query = "SELECT " + NAME + " FROM " + REACTION + " WHERE " + BIGG_ID + " = ? AND " + NAME + " <> ''"; return singleParamStatement(query, abbreviation); } @@ -498,7 +486,7 @@ public Optional getReactionName(String abbreviation) { * @param isReaction If true, the BiGG ID is treated as a reaction; if false, it is treated as a component. * @return A sorted set of URLs as strings, potentially filtered by the 'identifiers.org' domain. */ - public Set getResources(BiGGId biggId, boolean includeAnyURI, boolean isReaction) { + public Set getResources(BiGGId biggId, boolean includeAnyURI, boolean isReaction) throws SQLException { String type = isReaction ? REACTION : COMPONENT; Set resources = new TreeSet<>(); String query = format( @@ -515,8 +503,6 @@ public Set getResources(BiGGId biggId, boolean includeAnyURI, resources.add(new IdentifiersOrgURI(result)); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return resources; } @@ -548,7 +534,7 @@ private String getTypeQuery(boolean isReaction) { * @param abbreviation The abbreviation of the model for which the taxon ID is being queried. * @return An {@link Optional} containing the taxon ID if found; otherwise, an empty {@link Optional}. */ - public Optional getTaxonId(String abbreviation) { + public Optional getTaxonId(String abbreviation) throws SQLException { Integer result = null; String query = "SELECT " + TAXON_ID + " FROM " + GENOME + " g, " + MODEL + " m WHERE g." + ID + " = m." + GENOME_ID + " AND m." + BIGG_ID + " = ? AND " + TAXON_ID + " IS NOT NULL"; @@ -558,14 +544,12 @@ public Optional getTaxonId(String abbreviation) { try (ResultSet resultSet = pStatement.executeQuery()) { while (resultSet.next()) { if (result != null) { - logger.severe(format(MESSAGES.getString("QUERY_TAXON_MULTIPLE_RESULTS"), abbreviation)); + logger.info(format(MESSAGES.getString("QUERY_TAXON_MULTIPLE_RESULTS"), abbreviation)); } else { result = resultSet.getInt(1); } } } - } catch (SQLException exc) { - logger.warning(format(MESSAGES.getString("GET_TAXON_ERROR"), abbreviation, Utils.getMessage(exc))); } return result == null ? Optional.empty() : Optional.of(result); } @@ -583,7 +567,7 @@ public Optional getTaxonId(String abbreviation) { * @return The accession string which can be appended to the base URLs mentioned above. * If the query fails or no accession is found, an empty string is returned. */ - public String getGenomeAccesion(String id) { + public String getGenomeAccesion(String id) throws SQLException { String query = "SELECT g." + ACCESSION_VALUE + " FROM " + GENOME + " g, " + MODEL + " m WHERE m." + BIGG_ID + " = ? AND m." + GENOME_ID + " = g." + ID; String result = ""; @@ -596,8 +580,6 @@ public String getGenomeAccesion(String id) { result = resultSet.getString(1); } } - } catch (SQLException e) { - logger.warning(format(MESSAGES.getString("GENOME_ACCESSION_FAIL"), id)); } // The result should be non-empty as the query is expected to always return exactly one result. return result; @@ -613,7 +595,7 @@ public String getGenomeAccesion(String id) { * @return A Set of strings containing unique BiGG IDs from the specified table. If an SQL error occurs, * the returned set will be empty. */ - public Set getAllBiggIds(String table) { + public Set getAllBiggIds(String table) throws SQLException { Set biggIds = new LinkedHashSet<>(); String query = "SELECT " + BIGG_ID + " FROM " + table + " ORDER BY " + BIGG_ID; try (Connection connection = connectionPool.getConnection(); @@ -623,8 +605,6 @@ public Set getAllBiggIds(String table) { biggIds.add(resultSet.getString(1)); } } - } catch (SQLException exc) { - logger.warning(format(MESSAGES.getString("BIGGID_FOR_TABLE_FAIL"), table, Utils.getMessage(exc))); } return biggIds; } @@ -640,7 +620,7 @@ public Set getAllBiggIds(String table) { * @return An {@link Optional} containing the charge if it is unique and present; otherwise, an empty {@link Optional}. * If multiple unique charge values are found, a warning is logged. */ - public Optional getChargeByCompartment(String componentId, String compartmentId) { + public Optional getChargeByCompartment(String componentId, String compartmentId) throws SQLException { String query = "SELECT DISTINCT mcc." + CHARGE + " FROM " + MCC + " mcc, " + COMPARTMENTALIZED_COMPONENT + " cc, " + COMPONENT + " c, " + COMPARTMENT + " co WHERE c." + BIGG_ID + " = ? AND c." + ID + " = cc." + COMPONENT_ID + " AND co." + BIGG_ID + " = ? AND co." + ID + " = cc." + COMPARTMENT_ID + " and cc." + ID + " = mcc." @@ -650,7 +630,7 @@ public Optional getChargeByCompartment(String componentId, String compa return Optional.of(Integer.parseInt(results.iterator().next())); } else { if (results.size() > 1) { - logger.warning(format(MESSAGES.getString("CHARGE_NOT_UNIQUE_COMPARTMENT"), componentId, compartmentId)); + logger.info(format(MESSAGES.getString("CHARGE_NOT_UNIQUE_COMPARTMENT"), componentId, compartmentId)); } return Optional.empty(); } @@ -667,7 +647,7 @@ public Optional getChargeByCompartment(String componentId, String compa * @param compartmentOrModelId The BiGG ID of the compartment or model, used to replace the second placeholder in the query. * @return A Set of strings containing distinct charge values from the query results. If no valid results are found, returns an empty set. */ - private Set runChargeQuery(String query, String componentId, String compartmentOrModelId) { + private Set runChargeQuery(String query, String componentId, String compartmentOrModelId) throws SQLException { Set results = new HashSet<>(); try (Connection connection = connectionPool.getConnection(); PreparedStatement pStatement = connection.prepareStatement(query)) { @@ -678,8 +658,6 @@ private Set runChargeQuery(String query, String componentId, String comp results.add(resultSet.getString(1)); } } - } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); } return results.stream().filter(charge -> charge != null && !charge.isEmpty()).collect(Collectors.toSet()); } @@ -695,7 +673,7 @@ private Set runChargeQuery(String query, String componentId, String comp * @return An Optional containing the charge if exactly one distinct charge is found, otherwise an empty Optional. * If multiple distinct charges are found, a warning is logged. */ - public Optional getCharge(String componentId, String modelId) { + public Optional getCharge(String componentId, String modelId) throws SQLException { String query = "SELECT DISTINCT mcc." + CHARGE + "\n FROM " + COMPONENT + " c,\n" + COMPARTMENTALIZED_COMPONENT + " cc,\n" + MODEL + " m,\n" + MCC + " mcc\n WHERE c." + ID + " = cc." + COMPONENT_ID + " AND\n cc." + ID + " = mcc." + COMPARTMENTALIZED_COMPONENT_ID + " AND\n c." + BIGG_ID + " = ? AND\n m." + BIGG_ID + " = ? AND\n m." @@ -705,7 +683,7 @@ public Optional getCharge(String componentId, String modelId) { return Optional.of(Integer.parseInt(results.iterator().next())); } else { if (results.size() > 1) { - logger.warning(format(MESSAGES.getString("CHARGE_NOT_UNIQUE_MODEL"), componentId, modelId)); + logger.info(format(MESSAGES.getString("CHARGE_NOT_UNIQUE_MODEL"), componentId, modelId)); } return Optional.empty(); } @@ -720,7 +698,7 @@ public Optional getCharge(String componentId, String modelId) { * @param reactionId The BiGG ID of the reaction to be checked. * @return true if the reaction is a pseudoreaction, false otherwise. */ - public boolean isPseudoreaction(String reactionId) { + public boolean isPseudoreaction(String reactionId) throws SQLException { String query = "SELECT " + PSEUDOREACTION + " FROM " + REACTION + " WHERE " + BIGG_ID + " = ?"; Optional result = singleParamStatement(query, reactionId); return result.isPresent() && result.get().equals("t"); @@ -779,7 +757,7 @@ public Optional getBiggIdFromSynonym(String dataSourceId, String synonym } } } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); + logger.info(Utils.getMessage(exc)); } return Optional.empty(); @@ -853,12 +831,12 @@ public Collection getBiggIdsForReactionForeignId(RegistryURI ur } } } catch (SQLException exc) { - logger.warning(Utils.getMessage(exc)); + logger.info(Utils.getMessage(exc)); } return results; } - public boolean isCompartment(String id) { + public boolean isCompartment(String id) throws SQLException { if (BiGGDBCompartments.isEmpty()) { BiGGDBCompartments = getAllBiggIds("compartment"); } @@ -869,7 +847,7 @@ public boolean isCompartment(String id) { } - public boolean isDataSource(String id) { + public boolean isDataSource(String id) throws SQLException { if (BiGGDBDataSources.isEmpty()) { BiGGDBDataSources = getAllBiggIds("data_source"); } @@ -877,7 +855,7 @@ public boolean isDataSource(String id) { } - public boolean isMetabolite(String id) { + public boolean isMetabolite(String id) throws SQLException { if (BiGGDBMetabolites.isEmpty()) { BiGGDBMetabolites = getAllBiggIds("component"); } @@ -888,7 +866,7 @@ public boolean isMetabolite(String id) { } - public boolean isModel(String id) { + public boolean isModel(String id) throws SQLException { if (BiGGDBModels.isEmpty()) { BiGGDBModels = getAllBiggIds("model"); } @@ -896,7 +874,7 @@ public boolean isModel(String id) { } - public boolean isReaction(String id) { + public boolean isReaction(String id) throws SQLException { if (BiGGDBReactions.isEmpty()) { BiGGDBReactions = getAllBiggIds("reaction"); } diff --git a/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGId.java b/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGId.java index 45302b6e..0121cfa2 100644 --- a/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGId.java +++ b/src/main/java/edu/ucsd/sbrg/db/bigg/BiGGId.java @@ -9,6 +9,8 @@ import java.util.regex.Pattern; import de.zbit.util.ResourceManager; +import edu.ucsd.sbrg.io.parsers.cobra.MatlabParser; +import org.slf4j.LoggerFactory; /** @@ -36,13 +38,7 @@ */ public class BiGGId { - /** - * A {@link Logger} for this class. - */ - private static final Logger logger = Logger.getLogger(BiGGId.class.getName()); - /** - * Bundle for ModelPolisher logger messages - */ + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(BiGGId.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); /** * First part of BiGG ID, either R, M or G @@ -434,7 +430,7 @@ private void handleSpecialCases(String id) { } else if (compartmentMatcher.matches()) { setAbbreviation(id); } else { - logger.warning(format(MESSAGES.getString("BIGGID_CONVERSION_FAIL"), id)); + logger.info(format(MESSAGES.getString("BIGGID_CONVERSION_FAIL"), id)); setAbbreviation(id); } } diff --git a/src/main/java/edu/ucsd/sbrg/io/CombineArchive.java b/src/main/java/edu/ucsd/sbrg/io/CombineArchive.java index 3b7a66f4..2b48d53a 100644 --- a/src/main/java/edu/ucsd/sbrg/io/CombineArchive.java +++ b/src/main/java/edu/ucsd/sbrg/io/CombineArchive.java @@ -1,6 +1,9 @@ package edu.ucsd.sbrg.io; +import de.unirostock.sems.cbarchive.CombineArchiveException; import de.zbit.util.ResourceManager; +import org.jdom2.JDOMException; +import org.jetbrains.annotations.NotNull; import org.sbml.jsbml.Compartment; import org.sbml.jsbml.Reaction; import org.sbml.jsbml.SBMLDocument; @@ -13,17 +16,18 @@ import org.w3c.tidy.Tidy; import javax.xml.stream.XMLStreamException; +import javax.xml.transform.TransformerException; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; -import java.io.Writer; import java.net.URI; +import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; +import java.text.ParseException; import java.util.ResourceBundle; import java.util.logging.Logger; @@ -48,21 +52,12 @@ */ public class CombineArchive { - /** - * A {@link Logger} for this class. - */ private static final Logger logger = Logger.getLogger(CombineArchive.class.getName()); - /** - * Bundle for ModelPolisher logger messages - */ private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); - /** - * {@link SBMLDocument} to write glossary for - */ + public static final String COMBINE_SPECIFICATION = "https://identifiers.org/combine.specifications/sbml"; + public static final String RDF_MEDIATYPE = "https://purl.org/NET/mediatypes/application/rdf+xml"; + private final SBMLDocument doc; - /** - * Output location for the combine archive - */ private final File output; public CombineArchive(SBMLDocument doc, File output) { @@ -71,16 +66,16 @@ public CombineArchive(SBMLDocument doc, File output) { } - public void write() throws IOException, XMLStreamException { + public File write() throws IOException, XMLStreamException, ParseException, URISyntaxException, JDOMException, CombineArchiveException, TransformerException { writeGlossary(); - writeCombineArchive(); + return writeCombineArchive(); } /** * Writes the RDF glossary to a file. The glossary is generated from the SBML document associated with this instance. * The RDF file is named based on the output file's name with "_glossary.rdf" appended. - * + * * @throws XMLStreamException if there is an error in generating the glossary from the SBML document. * @throws IOException if there is an error writing the glossary to the file system. */ @@ -93,7 +88,33 @@ private void writeGlossary() throws XMLStreamException, IOException { // Log the location where the RDF file will be written logger.info(format(MESSAGES.getString("WRITE_RDF_FILE_INFO"), glossaryLocation)); // Write the glossary to the specified RDF file - writeTidyRDF(new File(glossaryLocation), glossary); + Tidy tidy = tidyParser(); + try (var out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(glossaryLocation), StandardCharsets.UTF_8)); + var in = new InputStreamReader(new ByteArrayInputStream(glossary.getBytes(StandardCharsets.UTF_8)), + StandardCharsets.UTF_8)) { + tidy.parse(in, out); + } + } + + private @NotNull Tidy tidyParser() { + Tidy tidy = new Tidy(); // obtain a new Tidy instance + tidy.setDropEmptyParas(false); + tidy.setHideComments(false); + tidy.setIndentContent(true); + tidy.setInputEncoding("UTF-8"); + tidy.setOutputEncoding("UTF-8"); + tidy.setQuiet(true); + tidy.setSmartIndent(true); + tidy.setTrimEmptyElements(true); + tidy.setWraplen(0); + tidy.setWrapAttVals(false); + tidy.setWrapScriptlets(true); + tidy.setLiteralAttribs(true); + tidy.setXmlOut(true); + tidy.setXmlSpace(true); + tidy.setXmlTags(true); + tidy.setSpaces(2); + return tidy; } @@ -153,8 +174,7 @@ private String getGlossary(SBMLDocument doc) throws XMLStreamException { * It then creates a new archive, adds the SBML model and RDF glossary as entries, and finally packs and closes the archive. * After packing, it cleans up the original files used in the archive. */ - private void writeCombineArchive() { - try { + private File writeCombineArchive() throws IOException, ParseException, JDOMException, CombineArchiveException, URISyntaxException, TransformerException { // Determine the base file path without extension String baseLocation = output.getAbsolutePath().substring(0, output.getAbsolutePath().lastIndexOf('.')); // Specify the locations for the glossary RDF and the COMBINE archive @@ -167,65 +187,26 @@ private void writeCombineArchive() { logger.severe(format("Failed to delete existing archive file \"{0}\"", caFile.getPath())); } - // Create a new COMBINE archive and add entries for the model XML and glossary RDF - de.unirostock.sems.cbarchive.CombineArchive ca = new de.unirostock.sems.cbarchive.CombineArchive(caFile); File outputXML = new File(output.getAbsolutePath()); File outputRDF = new File(glossaryLocation); - ca.addEntry(outputXML, "model.xml", new URI("http://identifiers.org/combine.specifications/sbml"), true); - ca.addEntry(outputRDF, "glossary.rdf", new URI("http://purl.org/NET/mediatypes/application/rdf+xml"), true); - logger.info(format(MESSAGES.getString("WRITE_RDF_FILE_INFO"), combineArcLocation)); - // Pack and close the archive - ca.pack(); - ca.close(); + // Create a new COMBINE archive and add entries for the model XML and glossary RDF + try(de.unirostock.sems.cbarchive.CombineArchive ca = new de.unirostock.sems.cbarchive.CombineArchive(caFile)) { + ca.addEntry(outputXML, "model.xml", new URI(COMBINE_SPECIFICATION), true); + ca.addEntry(outputRDF, "glossary.rdf", new URI(RDF_MEDIATYPE), true); + logger.info(format(MESSAGES.getString("WRITE_RDF_FILE_INFO"), combineArcLocation)); + + // Pack and close the archive + ca.pack(); + } // Delete the original files that were packed into the archive boolean rdfDeleted = outputRDF.delete(); boolean outputXMLDeleted = outputXML.delete(); logger.info(format(MESSAGES.getString("DELETE_FILE"), outputXML.getParent(), outputXMLDeleted)); logger.info(format(MESSAGES.getString("DELETE_FILE"), outputRDF.getParent(), rdfDeleted)); - } catch (Exception e) { - logger.warning("Exception while producing COMBINE Archive:"); - e.printStackTrace(); - } + return caFile; } - /** - * Writes a formatted RDF string to a file using the JTidy library to ensure the RDF content is well-formed XML. - * This method configures the Tidy parser for XML output and sets various formatting options to enhance readability. - * - * @param outputFile The file to which the formatted RDF content will be written. - * @param rdfString The RDF content in string format that needs to be formatted and written to the file. - * @throws FileNotFoundException if the outputFile cannot be opened for writing. - */ - private void writeTidyRDF(File outputFile, String rdfString) throws FileNotFoundException { - Tidy tidy = new Tidy(); // obtain a new Tidy instance - tidy.setDropEmptyParas(false); - tidy.setHideComments(false); - tidy.setIndentContent(true); - tidy.setInputEncoding("UTF-8"); - tidy.setOutputEncoding("UTF-8"); - tidy.setQuiet(true); - tidy.setSmartIndent(true); - tidy.setTrimEmptyElements(true); - tidy.setWraplen(0); - tidy.setWrapAttVals(false); - tidy.setWrapScriptlets(true); - tidy.setLiteralAttribs(true); - tidy.setXmlOut(true); - tidy.setXmlSpace(true); - tidy.setXmlTags(true); - tidy.setSpaces(2); - Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8)); - InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(rdfString.getBytes(StandardCharsets.UTF_8)), - StandardCharsets.UTF_8); - tidy.parse(in, out); - try { - in.close(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } } diff --git a/src/main/java/edu/ucsd/sbrg/io/DeleteOnCloseFileInputStream.java b/src/main/java/edu/ucsd/sbrg/io/DeleteOnCloseFileInputStream.java new file mode 100644 index 00000000..fdc4d293 --- /dev/null +++ b/src/main/java/edu/ucsd/sbrg/io/DeleteOnCloseFileInputStream.java @@ -0,0 +1,36 @@ +package edu.ucsd.sbrg.io; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class DeleteOnCloseFileInputStream extends FileInputStream { + + File file; + + public DeleteOnCloseFileInputStream(String s) throws FileNotFoundException { + this(new File(s)); + } + + public DeleteOnCloseFileInputStream(File file) throws FileNotFoundException { + super(file); + this.file = file; + } + + @SuppressWarnings("ThrowFromFinallyBlock") + public void close() throws IOException { + try { + super.close(); + } finally { + if (file != null) { + if (!file.delete()) { + throw new IOException("Could not delete file on close."); + } + file = null; + } + } + } +} + + diff --git a/src/main/java/edu/ucsd/sbrg/io/ModelReader.java b/src/main/java/edu/ucsd/sbrg/io/ModelReader.java index dd11fbc7..eb5d9452 100644 --- a/src/main/java/edu/ucsd/sbrg/io/ModelReader.java +++ b/src/main/java/edu/ucsd/sbrg/io/ModelReader.java @@ -3,16 +3,22 @@ import edu.ucsd.sbrg.parameters.SBOParameters; import edu.ucsd.sbrg.io.parsers.cobra.MatlabParser; import edu.ucsd.sbrg.io.parsers.json.JSONParser; +import edu.ucsd.sbrg.polishing.SBMLPolisher; import edu.ucsd.sbrg.resolver.Registry; import org.sbml.jsbml.SBMLDocument; import org.sbml.jsbml.SBMLReader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; import java.io.*; import java.util.Arrays; import java.util.stream.Collectors; +import static java.text.MessageFormat.format; + public class ModelReader { + private static final Logger logger = LoggerFactory.getLogger(ModelReader.class); private final SBOParameters sboParameters; private final Registry registry; @@ -23,18 +29,24 @@ public ModelReader(SBOParameters sboParameters, Registry registry) { } - public SBMLDocument read(File input) throws IOException, XMLStreamException { - var fileType = SBMLFileUtils.getFileType(input); - - return switch (fileType) { - case MAT_FILE -> new MatlabParser(sboParameters, registry).parse(input); - case JSON_FILE -> new JSONParser(registry).parse(input); - case SBML_FILE -> SBMLReader.read(input, new UpdateListener()); - case UNKNOWN -> throw new IllegalArgumentException("Could not identify file type. Supported file types are: " - + Arrays.stream(SBMLFileUtils.FileType.values()) - .map(SBMLFileUtils.FileType::name) - .collect(Collectors.joining(", "))); - }; + public SBMLDocument read(File input) throws ModelReaderException { + logger.debug(format("Read model file: {0}", input.toString())); + try { + var fileType = SBMLFileUtils.getFileType(input); + + return switch (fileType) { + case MAT_FILE -> new MatlabParser(sboParameters, registry).parse(input); + case JSON_FILE -> new JSONParser(registry).parse(input); + case SBML_FILE -> SBMLReader.read(input, new UpdateListener()); + case UNKNOWN -> + throw new IllegalArgumentException("Could not identify file type. Supported file types are: " + + Arrays.stream(SBMLFileUtils.FileType.values()) + .map(SBMLFileUtils.FileType::name) + .collect(Collectors.joining(", "))); + }; + + } catch (Exception e) { + throw new ModelReaderException("Error while reading input document.", e, input); + } } - } diff --git a/src/main/java/edu/ucsd/sbrg/io/ModelReaderException.java b/src/main/java/edu/ucsd/sbrg/io/ModelReaderException.java new file mode 100644 index 00000000..dc7243fc --- /dev/null +++ b/src/main/java/edu/ucsd/sbrg/io/ModelReaderException.java @@ -0,0 +1,17 @@ +package edu.ucsd.sbrg.io; + +import java.io.File; + +public class ModelReaderException extends Exception { + + private final File input; + + public ModelReaderException(String s, Exception e, File input) { + super(s, e); + this.input = input; + } + + public File input() { + return input; + } +} diff --git a/src/main/java/edu/ucsd/sbrg/io/ModelWriter.java b/src/main/java/edu/ucsd/sbrg/io/ModelWriter.java index 4eb96bc4..fe357ae1 100644 --- a/src/main/java/edu/ucsd/sbrg/io/ModelWriter.java +++ b/src/main/java/edu/ucsd/sbrg/io/ModelWriter.java @@ -1,74 +1,170 @@ package edu.ucsd.sbrg.io; -import de.zbit.io.ZIPUtils; +import de.unirostock.sems.cbarchive.CombineArchiveException; import de.zbit.util.ResourceManager; import edu.ucsd.sbrg.ModelPolisherOptions; import edu.ucsd.sbrg.io.parsers.json.JSONConverter; -import edu.ucsd.sbrg.parameters.OutputParameters; +import org.jdom2.JDOMException; +import org.jetbrains.annotations.NotNull; import org.sbml.jsbml.SBMLDocument; import org.sbml.jsbml.TidySBMLWriter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ResourceBundle; -import java.util.logging.Logger; +import javax.xml.transform.TransformerException; +import java.io.*; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.text.ParseException; import static java.text.MessageFormat.format; public class ModelWriter { + private static final Logger logger = LoggerFactory.getLogger(ModelWriter.class); + private final ModelPolisherOptions.OutputType outputType; - private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); - private static final Logger logger = Logger.getLogger(ModelWriter.class.getName()); - private final OutputParameters parameters; + public ModelWriter(ModelPolisherOptions.OutputType outputType) { + this.outputType = outputType; + } - public ModelWriter(OutputParameters parameters) { - this.parameters = parameters; + public InputStream write(SBMLDocument doc) throws ModelWriterException { + logger.debug("Write document to InputStream."); + try { + return switch (outputType) { + case SBML -> writeSBML(doc); + case JSON -> writeJSON(doc); + case COMBINE -> writeCOMBINE(doc); + }; + } catch (Exception e) { + throw new ModelWriterException("Error while writing output document.", e, doc, null); + } } + public File write(SBMLDocument doc, File output) throws ModelWriterException { + logger.debug(format("Write document to File: {0}", output.toString())); - public void write(SBMLDocument doc, File output, String modelPolisherVersion) throws IOException, XMLStreamException { - // Convert and write the document to JSON if specified - if (parameters.writeJSON()) { - String out = output.getAbsolutePath().replaceAll("\\.xml", ".json"); - try (BufferedWriter writer = new BufferedWriter(new FileWriter(out))) { - writer.write(JSONConverter.getJSONDocument(doc)); - } - } - // writing polished model - logger.info(format(MESSAGES.getString("WRITE_FILE_INFO"), output.getAbsolutePath())); - TidySBMLWriter.write(doc, output, getClass().getSimpleName(), modelPolisherVersion, ' ', (short) 2); - // Handle COMBINE archive creation if specified - if (parameters.outputCOMBINE()) { - CombineArchive combineArchive = new CombineArchive(doc, output); - combineArchive.write(); - } - // Handle file compression based on the specified method - if (parameters.compression() != ModelPolisherOptions.Compression.NONE) { - writeZIP(output); + try { + return switch (outputType) { + case SBML -> writeSBML(doc, output); + case JSON -> writeJSON(doc, output); + case COMBINE -> writeCOMBINE(doc, output); + }; + } catch (Exception e) { + throw new ModelWriterException("Error while writing output document.", e, doc, output); } } - private void writeZIP(File output) throws IOException { - String fileExtension = parameters.compression().getFileExtension(); - String archive = output.getAbsolutePath() + "." + fileExtension; - logger.info(format(MESSAGES.getString("ARCHIVE"), archive)); - switch (parameters.compression()) { - case ZIP: - ZIPUtils.ZIPcompress(new String[] {output.getAbsolutePath()}, archive, "SBML Archive", true); - break; - case GZIP: - ZIPUtils.GZip(output.getAbsolutePath(), archive); - break; - default: - break; + private InputStream writeSBML(SBMLDocument doc) throws IOException, XMLStreamException { + PipedInputStream result = new PipedInputStream(); + PipedOutputStream pout = new PipedOutputStream(result); + + // Create a new thread to handle the writing to the piped output stream + new Thread(() -> { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + TidySBMLWriter.write( + doc, + baos, + getClass().getSimpleName(), + getClass().getPackage().getImplementationVersion(), + ' ', + (short) 2); + baos.writeTo(pout); + } catch (IOException | XMLStreamException e) { + // Handle exceptions appropriately + logger.error("Error in writing.", e); + } finally { + // Ensure the PipedOutputStream is closed properly + try { + pout.close(); + } catch (IOException e) { + logger.error("Error in writing.", e); + } + } + }).start(); + + return result; + } + + private InputStream writeJSON(SBMLDocument doc) throws ModelWriterException { + PipedOutputStream out = new PipedOutputStream(); + try (var writer = new BufferedWriter(new OutputStreamWriter(out))) { + writer.write(JSONConverter.getJSONDocument(doc)); + return new PipedInputStream(out); + } catch (IOException e) { + throw new ModelWriterException("Error while converting to JSON.", e, doc, null); } - // Delete the original output file if compression is successful + } + + private InputStream writeCOMBINE(SBMLDocument doc) throws IOException, XMLStreamException, ParseException, URISyntaxException, JDOMException, CombineArchiveException, TransformerException, ModelWriterException { + File f = Files.createTempFile("", ".xml").toFile(); + TidySBMLWriter.write( + doc, + f, + getClass().getSimpleName(), + getClass().getPackage().getImplementationVersion(), + ' ', + (short) 2); + CombineArchive combineArchive = new CombineArchive(doc, f); + File combineArchiveFile = combineArchive.write(); + return new DeleteOnCloseFileInputStream(combineArchiveFile); + } + + + private File writeCOMBINE(SBMLDocument doc, File output) throws IOException, XMLStreamException, ParseException, URISyntaxException, JDOMException, CombineArchiveException, TransformerException, ModelWriterException { + File f = Files.createTempFile("", ".xml").toFile(); + TidySBMLWriter.write( + doc, + f, + getClass().getSimpleName(), + getClass().getPackage().getImplementationVersion(), + ' ', + (short) 2); + CombineArchive combineArchive = new CombineArchive(doc, output); + File combineArchiveFile = combineArchive.write(); if (!output.delete()) { - logger.warning(format(MESSAGES.getString("REMOVE_ZIP_INPUT_FAIL"), output.getAbsolutePath())); + throw new ModelWriterException("Could not delete file after COMBINE archive creation.", + doc, output, combineArchiveFile); + } + return combineArchiveFile; + } + + private static @NotNull File writeJSON(SBMLDocument doc, File output) throws IOException { + String out = output.getAbsolutePath().replaceAll("\\.xml", ".json"); + try (var writer = new BufferedWriter(new FileWriter(out))) { + writer.write(JSONConverter.getJSONDocument(doc)); } + return new File(out); } + private File writeSBML(SBMLDocument doc, File output) throws XMLStreamException, IOException { + TidySBMLWriter.write( + doc, + output, + getClass().getSimpleName(), + getClass().getPackage().getImplementationVersion(), + ' ', + (short) 2); + return output; + } + +// private File writeZIP(File output) throws IOException { +// String fileExtension = parameters.compression().getFileExtension(); +// String archive = output.getAbsolutePath() + "." + fileExtension; +// logger.info(format(MESSAGES.getString("ARCHIVE"), archive)); +// switch (parameters.compression()) { +// case ZIP: +// ZIPUtils.ZIPcompress(new String[] {output.getAbsolutePath()}, archive, "SBML Archive", true); +// break; +// case GZIP: +// ZIPUtils.GZip(output.getAbsolutePath(), archive); +// break; +// default: +// break; +// } +// // Delete the original output file if outputType is successful +// +// return new File(archive); +// } + } diff --git a/src/main/java/edu/ucsd/sbrg/io/ModelWriterException.java b/src/main/java/edu/ucsd/sbrg/io/ModelWriterException.java new file mode 100644 index 00000000..bd0cd75b --- /dev/null +++ b/src/main/java/edu/ucsd/sbrg/io/ModelWriterException.java @@ -0,0 +1,38 @@ +package edu.ucsd.sbrg.io; + +import org.sbml.jsbml.SBMLDocument; + +import java.io.File; + +public class ModelWriterException extends Exception{ + + private final SBMLDocument doc; + private final File output; + private final File archiveFile; + + public ModelWriterException(String s, Exception e, SBMLDocument doc, File output) { + super(s, e); + this.doc = doc; + this.output = output; + this.archiveFile = null; + } + + public ModelWriterException(String s, SBMLDocument doc, File output, File archiveFile) { + super(s); + this.doc = doc; + this.output = output; + this.archiveFile = archiveFile; + } + + public SBMLDocument doc() { + return doc; + } + + public File output() { + return output; + } + + public File archiveFile() { + return archiveFile; + } +} diff --git a/src/main/java/edu/ucsd/sbrg/io/SBMLFileUtils.java b/src/main/java/edu/ucsd/sbrg/io/SBMLFileUtils.java index 122077cf..3ca45b61 100644 --- a/src/main/java/edu/ucsd/sbrg/io/SBMLFileUtils.java +++ b/src/main/java/edu/ucsd/sbrg/io/SBMLFileUtils.java @@ -102,7 +102,7 @@ public static void checkCreateOutDir(File output) { } else { logger.severe(format(MESSAGES.getString("DIRECTORY_CREATION_FAILED"), output.getAbsolutePath())); // TODO: grace - throw new RuntimeException(); + throw new RuntimeException(format(MESSAGES.getString("DIRECTORY_CREATION_FAILED"), output.getAbsolutePath())); } } // output is a file @@ -116,7 +116,7 @@ public static void checkCreateOutDir(File output) { logger.severe( format(MESSAGES.getString("DIRECTORY_CREATION_FAILED"), output.getParentFile().getAbsolutePath())); // TODO: grace - throw new RuntimeException(); + throw new RuntimeException(format(MESSAGES.getString("DIRECTORY_CREATION_FAILED"), output.getParentFile().getAbsolutePath())); } } } diff --git a/src/main/java/edu/ucsd/sbrg/io/parsers/cobra/MatlabParser.java b/src/main/java/edu/ucsd/sbrg/io/parsers/cobra/MatlabParser.java index 5e4c8813..92607d70 100644 --- a/src/main/java/edu/ucsd/sbrg/io/parsers/cobra/MatlabParser.java +++ b/src/main/java/edu/ucsd/sbrg/io/parsers/cobra/MatlabParser.java @@ -2,6 +2,7 @@ import de.zbit.sbml.util.SBMLtools; import de.zbit.util.ResourceManager; +import edu.ucsd.sbrg.io.parsers.json.JSONParser; import edu.ucsd.sbrg.parameters.SBOParameters; import edu.ucsd.sbrg.resolver.Registry; import edu.ucsd.sbrg.util.GPRParser; @@ -20,6 +21,7 @@ import org.sbml.jsbml.ext.groups.GroupsConstants; import org.sbml.jsbml.ext.groups.GroupsModelPlugin; import org.sbml.jsbml.util.ModelBuilder; +import org.slf4j.LoggerFactory; import us.hebi.matlab.mat.format.Mat5; import us.hebi.matlab.mat.format.Mat5File; import us.hebi.matlab.mat.types.Array; @@ -44,13 +46,7 @@ */ public class MatlabParser { - /** - * A {@link Logger} for this class. - */ - private static final Logger logger = Logger.getLogger(MatlabParser.class.getName()); - /** - * Bundle for ModelPolisher logger messages - */ + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(MatlabParser.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private static MatlabFields matlabFields; private final SBOParameters sboParameters; @@ -87,12 +83,12 @@ private SBMLDocument parseModel(Mat5File matFile) { } } if (modelName.isEmpty()) { - logger.severe("Model name is empty for matlab model, aborting"); + logger.info("Model name is empty for matlab model, aborting"); return new SBMLDocument(); } Struct modelStruct = matFile.getStruct(modelName); if (!Arrays.equals(modelStruct.getDimensions(), new int[] {1, 1})) { - logger.severe("Model struct dimensions are wrong, aborting"); + logger.info("Model struct dimensions are wrong, aborting"); return new SBMLDocument(); } ModelBuilder builder = new ModelBuilder(3, 1); @@ -134,7 +130,7 @@ private void fixFields(Struct modelStruct) { modelStruct.remove(fieldName); modelStruct.set(match, array); } else { - logger.warning(format("Could not resolve field {0} to known variant", fieldName)); + logger.info(format("Could not resolve field {0} to known variant", fieldName)); } } } @@ -222,7 +218,7 @@ private void parseGPRs(Model model) { for (int i = 0; i < grRules.getNumElements(); i++) { String geneReactionRule = COBRAUtils.asString(grRules.get(i), ModelField.grRules.name(), i + 1); if (model.getReaction(i) == null) { - logger.severe(format(MESSAGES.getString("CREATE_GPR_FAILED"), i)); + logger.info(format(MESSAGES.getString("CREATE_GPR_FAILED"), i)); } else { GPRParser.parseGPR(model.getReaction(i), geneReactionRule, sboParameters.omitGenericTerms()); } @@ -251,7 +247,7 @@ private void parseSubsystems(Model model) { if (model.getReaction(i) != null) { SBMLUtils.createSubsystemLink(model.getReaction(i), group.createMember()); } else { - logger.severe(format(MESSAGES.getString("SUBSYS_LINK_ERROR"), i)); + logger.info(format(MESSAGES.getString("SUBSYS_LINK_ERROR"), i)); } } } @@ -268,10 +264,10 @@ private void parseCSense(Model model) { char c = csense.getChar(0, i); // TODO: only 'E' (equality) is supported for now! if (c != 'E' && model.getListOfSpecies().size() > i) { - logger.severe(format(MESSAGES.getString("NEQ_RELATION_UNSUPPORTED"), model.getSpecies(i).getId())); + logger.info(format(MESSAGES.getString("NEQ_RELATION_UNSUPPORTED"), model.getSpecies(i).getId())); } } catch (Exception e) { - logger.severe(e.toString()); + logger.info(e.toString()); return; } } @@ -307,7 +303,7 @@ private void parseBValue(Model model) { double bVal = b.getDouble(i); if (bVal != 0d && model.getListOfSpecies().size() > i) { // TODO: this should be incorporated into FBC version 3. - logger.warning(format(MESSAGES.getString("B_VALUE_UNSUPPORTED"), bVal, model.getSpecies(i).getId())); + logger.info(format(MESSAGES.getString("B_VALUE_UNSUPPORTED"), bVal, model.getSpecies(i).getId())); } } }); diff --git a/src/main/java/edu/ucsd/sbrg/io/parsers/json/JSONParser.java b/src/main/java/edu/ucsd/sbrg/io/parsers/json/JSONParser.java index 71e032d1..b1416497 100644 --- a/src/main/java/edu/ucsd/sbrg/io/parsers/json/JSONParser.java +++ b/src/main/java/edu/ucsd/sbrg/io/parsers/json/JSONParser.java @@ -22,6 +22,7 @@ import edu.ucsd.sbrg.resolver.Registry; import edu.ucsd.sbrg.resolver.RegistryURI; import edu.ucsd.sbrg.resolver.identifiersorg.IdentifiersOrgURI; +import edu.ucsd.sbrg.util.SBMLFix; import org.sbml.jsbml.CVTerm; import org.sbml.jsbml.Compartment; import org.sbml.jsbml.Model; @@ -55,19 +56,14 @@ import edu.ucsd.sbrg.util.GPRParser; import edu.ucsd.sbrg.util.SBMLUtils; import edu.ucsd.sbrg.io.UpdateListener; +import org.slf4j.LoggerFactory; /** * @author Thomas Jakob Zajac */ public class JSONParser { - /** - * A {@link Logger} for this class. - */ - private static final Logger logger = Logger.getLogger(JSONParser.class.getName()); - /** - * Bundle for ModelPolisher logger messages - */ + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(JSONParser.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private final Registry registry; @@ -145,7 +141,7 @@ public void parseAnnotation(SBase node, Object annotation) { annotations.addAll(parseAnnotation(entry)); } } else { - logger.severe(format(MESSAGES.getString("OPEN_ISSUE_ANNOTATION"), annotation.getClass().getName())); + logger.info(format(MESSAGES.getString("OPEN_ISSUE_ANNOTATION"), annotation.getClass().getName())); } if (!annotations.isEmpty()) { CVTerm term = new CVTerm(); @@ -171,7 +167,7 @@ private Set parseAnnotation(Map.Entry entry) { checkResource(providerCode, id).map(annotations::add); } } else { - logger.severe(format(MESSAGES.getString("OPEN_ISSUE_ID_FORMAT"), ids.getClass().getName())); + logger.info(format(MESSAGES.getString("OPEN_ISSUE_ID_FORMAT"), ids.getClass().getName())); } return annotations; } @@ -221,7 +217,7 @@ public void parseNotes(SBase node, Object notes) { e.printStackTrace(); } } else { - logger.severe(format(MESSAGES.getString("OPEN_ISSUE_NOTES_FORMAT"), notes.getClass().getName())); + logger.info(format(MESSAGES.getString("OPEN_ISSUE_NOTES_FORMAT"), notes.getClass().getName())); } } @@ -240,7 +236,7 @@ private String parseNotes(Map.Entry entry) { ((List) value).forEach(items::add); note = key + ":" + items; } else { - logger.severe(format(MESSAGES.getString("OPEN_ISSUE_NOTES_CONTENT"), value.getClass().getName())); + logger.info(format(MESSAGES.getString("OPEN_ISSUE_NOTES_CONTENT"), value.getClass().getName())); } return note; } @@ -279,7 +275,7 @@ private void parseMetabolites(ModelBuilder builder, List metabolites String id = metabolite.getId(); BiGGId.createMetaboliteId(id).ifPresent(metId -> { if (model.getSpecies(metId.toBiGGId()) != null) { - logger.warning(format(MESSAGES.getString("DUPLICATE_SPECIES_ID"), id)); + logger.info(format(MESSAGES.getString("DUPLICATE_SPECIES_ID"), id)); } else { parseMetabolite(model, metabolite, metId); } @@ -306,7 +302,7 @@ public void parseMetabolite(Model model, Metabolite metabolite, BiGGId biggId) { specPlug.setChemicalFormula(formula); validFormula = true; } catch (IllegalArgumentException exc) { - logger.warning(format(MESSAGES.getString("INVALID_SPECIES_FORMULA"), biggId.toBiGGId(), formula)); + logger.info(format(MESSAGES.getString("INVALID_SPECIES_FORMULA"), biggId.toBiGGId(), formula)); } } specPlug.setCharge(charge); @@ -342,7 +338,7 @@ private void parseGenes(ModelBuilder builder, List genes) { BiGGId.createGeneId(id).ifPresent(geneId -> { FBCModelPlugin modelPlug = (FBCModelPlugin) model.getPlugin(FBCConstants.shortLabel); if (modelPlug.getGeneProduct(geneId.toBiGGId()) != null) { - logger.warning(format(MESSAGES.getString("DUPLICATE_GENE_ID"), id)); + logger.info(format(MESSAGES.getString("DUPLICATE_GENE_ID"), id)); } else { parseGene(model, gene, geneId.toBiGGId()); } @@ -377,7 +373,7 @@ private void parseReactions(ModelBuilder builder, List reactions) { // Add prefix for BiGGId BiGGId.createReactionId(id).ifPresent(reactionId -> { if (builder.getModel().getReaction(reactionId.toBiGGId()) != null) { - logger.warning(format(MESSAGES.getString("DUPLICATE_REACTION_ID"), id)); + logger.info(format(MESSAGES.getString("DUPLICATE_REACTION_ID"), id)); } else { parseReaction(builder, reaction, reactionId.toBiGGId()); } diff --git a/src/main/java/edu/ucsd/sbrg/parameters/CommandLineParameters.java b/src/main/java/edu/ucsd/sbrg/parameters/CommandLineParameters.java index 05002f48..c7496e08 100644 --- a/src/main/java/edu/ucsd/sbrg/parameters/CommandLineParameters.java +++ b/src/main/java/edu/ucsd/sbrg/parameters/CommandLineParameters.java @@ -13,9 +13,10 @@ public class CommandLineParameters { private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private final File input; + private final File output; protected boolean sbmlValidation = ModelPolisherOptions.SBML_VALIDATION.getDefaultValue(); + protected ModelPolisherOptions.OutputType outputType = ModelPolisherOptions.OUTPUT_TYPE.getDefaultValue(); - private final OutputParameters outputParameters; private final SBOParameters sboParameters; private final PolishingParameters polishingParameters; private final AnnotationParameters annotationParameters; @@ -26,9 +27,15 @@ public CommandLineParameters(SBProperties args) throws IllegalArgumentException if (inPath == null) { throw new IllegalArgumentException(MESSAGES.getString("PARAM_INPUT_MISSING")); } + + String outPath = args.getProperty(IOOptions.OUTPUT); + if (outPath == null) { + throw new IllegalArgumentException(MESSAGES.getString("PARAM_OUTPUT_MISSING")); + } + output = new File(outPath); input = new File(inPath); sbmlValidation = args.getBooleanProperty(ModelPolisherOptions.SBML_VALIDATION); - outputParameters = new OutputParameters(args); + outputType = ModelPolisherOptions.OutputType.valueOf(args.getProperty(ModelPolisherOptions.OUTPUT_TYPE)); annotationParameters = new AnnotationParameters(args); sboParameters = new SBOParameters(args); polishingParameters = new PolishingParameters(args); @@ -38,12 +45,16 @@ public File input() { return input; } + public File output() { + return output; + } + public boolean SBMLValidation() { return sbmlValidation; } - public OutputParameters outputParameters() { - return outputParameters; + public ModelPolisherOptions.OutputType outputType() { + return outputType; } public AnnotationParameters annotationParameters() { @@ -57,4 +68,5 @@ public SBOParameters sboParameters() { public PolishingParameters polishingParameters() { return polishingParameters; } + } diff --git a/src/main/java/edu/ucsd/sbrg/parameters/OutputParameters.java b/src/main/java/edu/ucsd/sbrg/parameters/OutputParameters.java deleted file mode 100644 index 50c2a812..00000000 --- a/src/main/java/edu/ucsd/sbrg/parameters/OutputParameters.java +++ /dev/null @@ -1,55 +0,0 @@ -package edu.ucsd.sbrg.parameters; - -import com.fasterxml.jackson.annotation.JsonProperty; -import de.zbit.util.ResourceManager; -import de.zbit.util.prefs.SBProperties; -import edu.ucsd.sbrg.ModelPolisherOptions; -import edu.ucsd.sbrg.io.IOOptions; - -import java.io.File; -import java.util.ResourceBundle; - - -public class OutputParameters { - private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); - - @JsonProperty("output-file") - private File outputFile = IOOptions.OUTPUT.getDefaultValue(); - @JsonProperty("compression") - protected ModelPolisherOptions.Compression compression = ModelPolisherOptions.COMPRESSION_TYPE.getDefaultValue(); - @JsonProperty("output-combine") - protected boolean outputCOMBINE = ModelPolisherOptions.OUTPUT_COMBINE.getDefaultValue(); - @JsonProperty("write-json") - protected boolean writeJSON = ModelPolisherOptions.WRITE_JSON.getDefaultValue(); - - public OutputParameters() { - } - - public OutputParameters(SBProperties args) { - String outPath = args.getProperty(IOOptions.OUTPUT); - if (outPath == null) { - throw new IllegalArgumentException(MESSAGES.getString("PARAM_OUTPUT_MISSING")); - } - outputFile = new File(outPath); - outputCOMBINE = args.getBooleanProperty(ModelPolisherOptions.OUTPUT_COMBINE); - compression = ModelPolisherOptions.Compression.valueOf(args.getProperty(ModelPolisherOptions.COMPRESSION_TYPE)); - writeJSON = args.getBooleanProperty(ModelPolisherOptions.WRITE_JSON); - } - - public boolean outputCOMBINE() { - return outputCOMBINE; - } - - public ModelPolisherOptions.Compression compression() { - return compression; - } - - public boolean writeJSON() { - return writeJSON; - } - - public File outputFile() { - return outputFile; - } - -} diff --git a/src/main/java/edu/ucsd/sbrg/parameters/Parameters.java b/src/main/java/edu/ucsd/sbrg/parameters/Parameters.java index 9f72b135..d005228e 100644 --- a/src/main/java/edu/ucsd/sbrg/parameters/Parameters.java +++ b/src/main/java/edu/ucsd/sbrg/parameters/Parameters.java @@ -11,10 +11,12 @@ public class Parameters { private AnnotationParameters annotation = new AnnotationParameters(); @JsonProperty("sbo-terms") private SBOParameters sboTerms = new SBOParameters(); - @JsonProperty("output") - private OutputParameters output = new OutputParameters(); @JsonProperty("sbml-validation") protected boolean sbmlValidation = ModelPolisherOptions.SBML_VALIDATION.getDefaultValue(); + @JsonProperty("outputType") + protected ModelPolisherOptions.OutputType outputType = ModelPolisherOptions.OUTPUT_TYPE.getDefaultValue(); + + public Parameters() {} public PolishingParameters polishing() { return polishing; @@ -28,11 +30,11 @@ public SBOParameters sboTerms() { return sboTerms; } - public OutputParameters output() { - return output; - } - public boolean sbmlValidation() { return sbmlValidation; } + + public ModelPolisherOptions.OutputType outputType() { + return outputType; + } } diff --git a/src/main/java/edu/ucsd/sbrg/polishing/AbstractPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/AbstractPolisher.java index 6bc0a0bf..eb9bd3e4 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/AbstractPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/AbstractPolisher.java @@ -39,6 +39,12 @@ protected void statusReport(String text, Object element) { } } + protected void diffReport(String elementType, Object element1, Object element2) { + for (var o : observers) { + o.update(new ProgressUpdate(elementType, List.of(element1, element2), ReportType.DATA)); + } + } + public List getObservers() { return observers; } diff --git a/src/main/java/edu/ucsd/sbrg/polishing/AnnotationPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/AnnotationPolisher.java index f91caea3..64cf8612 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/AnnotationPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/AnnotationPolisher.java @@ -6,12 +6,18 @@ import edu.ucsd.sbrg.reporting.ProgressObserver; import org.sbml.jsbml.Annotation; import org.sbml.jsbml.CVTerm; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashSet; import java.util.List; import java.util.Set; +import static java.text.MessageFormat.format; + + public class AnnotationPolisher extends AbstractPolisher { + private static final Logger logger = LoggerFactory.getLogger(AnnotationPolisher.class); public AnnotationPolisher(PolishingParameters polishingParameters, Registry registry) { super(polishingParameters, registry); @@ -32,6 +38,7 @@ public AnnotationPolisher(PolishingParameters polishingParameters, Registry regi * @param annotation The {@link Annotation} object associated with an SBML entity that contains CV Terms to be processed. */ public void polish(Annotation annotation) { + logger.trace(format("Polish Annotation: {0}", annotation.toString())); for (CVTerm term : annotation.getListOfCVTerms()) { Set resources = new HashSet<>(); for (String resource : term.getResources()) { diff --git a/src/main/java/edu/ucsd/sbrg/polishing/CompartmentPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/CompartmentPolisher.java index db265013..3e162498 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/CompartmentPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/CompartmentPolisher.java @@ -3,7 +3,6 @@ import static java.text.MessageFormat.format; import java.util.ResourceBundle; -import java.util.logging.Logger; import java.util.List; import edu.ucsd.sbrg.parameters.PolishingParameters; @@ -15,6 +14,8 @@ import de.zbit.util.ResourceManager; import edu.ucsd.sbrg.db.bigg.BiGGId; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * This class is responsible for polishing the properties of a compartment in an SBML model to ensure @@ -22,8 +23,7 @@ * and ensures that necessary attributes like units and spatial dimensions are appropriately set. */ public class CompartmentPolisher extends AbstractPolisher { - - private final static Logger logger = Logger.getLogger(CompartmentPolisher.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(CompartmentPolisher.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); public CompartmentPolisher(PolishingParameters polishingParameters, Registry registry, List observers) { @@ -38,7 +38,9 @@ public CompartmentPolisher(PolishingParameters polishingParameters, Registry reg */ @Override public void polish(List compartments) { + logger.debug("Polish Compartments"); for (Compartment compartment : compartments) { + diffReport("compartment", compartment.clone(), compartment); statusReport("Polishing Compartments (3/9) ", compartment); polish(compartment); } @@ -61,7 +63,7 @@ public void polish(Compartment compartment) { } else { // Attempt to remove the 'C_' prefix from the compartment ID, log a warning if the format is incorrect BiGGId.extractCompartmentCode(compartment.getId()).ifPresentOrElse(compartment::setId, - () -> logger.warning(format(MESSAGES.getString("COMPARTMENT_CODE_WRONG_FORMAT"), compartment.getId()))); + () -> logger.info(format(MESSAGES.getString("COMPARTMENT_CODE_WRONG_FORMAT"), compartment.getId()))); } // Set the SBOTerm to indicate an implicit compartment diff --git a/src/main/java/edu/ucsd/sbrg/polishing/ModelPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/ModelPolisher.java index 66476509..15cd7a78 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/ModelPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/ModelPolisher.java @@ -22,10 +22,11 @@ import edu.ucsd.sbrg.resolver.Registry; import org.sbml.jsbml.*; import org.sbml.jsbml.ext.fbc.FBCConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.ResourceBundle; -import java.util.logging.Logger; import static java.text.MessageFormat.format; @@ -40,7 +41,7 @@ */ public class ModelPolisher extends AbstractPolisher { - private static final Logger logger = Logger.getLogger(ModelPolisher.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ModelPolisher.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private final SBOParameters sboParameters; @@ -64,9 +65,7 @@ public ModelPolisher(PolishingParameters polishingParameters, SBOParameters sboP */ @Override public void polish(Model model) { - // Log the start of processing the model. - logger.info(format(MESSAGES.getString("PROCESSING_MODEL"), model.getId())); - + logger.debug(format(MESSAGES.getString("PROCESSING_MODEL"), model.toString())); statusReport("Polishing Model (1/9) ", model); // Delegate polishing tasks @@ -78,6 +77,7 @@ public void polish(Model model) { new ParametersPolisher(polishingParameters, registry, getObservers()).polish(model.getListOfParameters()); + diffReport("modelAnnotation", model.getAnnotation().clone(), model.getAnnotation()); new AnnotationPolisher(polishingParameters, registry, getObservers()).polish(model.getAnnotation()); new ReactionsPolisher(polishingParameters, sboParameters, registry, getObservers()).polish(model.getListOfReactions()); diff --git a/src/main/java/edu/ucsd/sbrg/polishing/ParametersPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/ParametersPolisher.java index a0024ffe..ead86ee4 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/ParametersPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/ParametersPolisher.java @@ -4,10 +4,15 @@ import edu.ucsd.sbrg.reporting.ProgressObserver; import edu.ucsd.sbrg.resolver.Registry; import org.sbml.jsbml.Parameter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; +import static java.text.MessageFormat.format; + public class ParametersPolisher extends AbstractPolisher { + private static final Logger logger = LoggerFactory.getLogger(ParametersPolisher.class); public ParametersPolisher(PolishingParameters parameters, Registry registry, List observers) { super(parameters, registry, observers); @@ -19,7 +24,9 @@ public ParametersPolisher(PolishingParameters parameters, Registry registry, Lis */ @Override public void polish(List modelParameters) { + logger.debug("Polish Parameters"); for (Parameter parameter : modelParameters) { + diffReport("parameter", parameter.clone(), parameter); statusReport("Polishing Parameters (9/9) ", parameter); polish(parameter); } diff --git a/src/main/java/edu/ucsd/sbrg/polishing/ReactionsPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/ReactionsPolisher.java index 9a0bded7..662d1c89 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/ReactionsPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/ReactionsPolisher.java @@ -14,11 +14,12 @@ import org.sbml.jsbml.ext.fbc.*; import org.sbml.jsbml.util.ValuePair; import org.sbml.jsbml.xml.XMLNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.Optional; import java.util.ResourceBundle; -import java.util.logging.Logger; import java.util.stream.Collectors; import static java.text.MessageFormat.format; @@ -37,7 +38,7 @@ */ public class ReactionsPolisher extends AbstractPolisher { - private final static Logger logger = Logger.getLogger(ReactionsPolisher.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ReactionsPolisher.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private final GeneProductAssociationsProcessor gpaPolisher; @@ -62,6 +63,8 @@ public ReactionsPolisher(PolishingParameters polishingParameters, SBOParameters */ @Override public void polish(List reactions) { + logger.debug("Polish Reactions"); + var iterator = reactions.iterator(); while (iterator.hasNext()) { var reaction = iterator.next(); @@ -71,12 +74,13 @@ public void polish(List reactions) { String id = reaction.getId(); if (id.isEmpty()) { if (reaction.isSetName()) { - logger.severe(format(MESSAGES.getString("REACTION_MISSING_ID"), reaction.getName())); + logger.debug(format(MESSAGES.getString("REACTION_MISSING_ID"), reaction.getName())); } else { - logger.severe(MESSAGES.getString("REACTION_MISSING_ID_NAME")); + logger.debug(MESSAGES.getString("REACTION_MISSING_ID_NAME")); } iterator.remove(); } else { + diffReport("reaction", reaction.clone(), reaction); polish(reaction); } } @@ -89,7 +93,9 @@ public void polish(List reactions) { * */ @SuppressWarnings("deprecated") + @Override public void polish(Reaction reaction) { + var originalReaction = reaction.clone(); // Process any external resources linked via annotations in the reaction new AnnotationPolisher(polishingParameters, registry).polish(reaction.getAnnotation()); // Check and set the compartment of the reaction based on its reactants and products @@ -237,13 +243,13 @@ private void checkBalance(Reaction reaction) { AtomCheckResult defects = AtomBalanceCheck.checkAtomBalance(reaction, 1); if ((defects != null) && (defects.hasDefects())) { // Log warning if atom defects are found - logger.warning(format(MESSAGES.getString("ATOMS_MISSING"), reaction.getId(), defects.getDefects().toString())); + logger.trace(format(MESSAGES.getString("ATOMS_MISSING"), reaction.getId(), defects.getDefects().toString())); } else if (defects == null) { // Log failure to check atom balance - logger.fine(format(MESSAGES.getString("CHECK_ATOM_BALANCE_FAILED"), reaction.getId())); + logger.trace(format(MESSAGES.getString("CHECK_ATOM_BALANCE_FAILED"), reaction.getId())); } else { // Log successful atom balance check - logger.fine(format(MESSAGES.getString("ATOMS_OK"), reaction.getId())); + logger.trace(format(MESSAGES.getString("ATOMS_OK"), reaction.getId())); } } } diff --git a/src/main/java/edu/ucsd/sbrg/polishing/SBMLPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/SBMLPolisher.java index 09aa8cf4..18739079 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/SBMLPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/SBMLPolisher.java @@ -10,14 +10,17 @@ import org.sbml.jsbml.ext.fbc.converters.CobraToFbcV2Converter; import org.sbml.jsbml.util.SBMLtools; import org.sbml.jsbml.util.ValuePair; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.ResourceBundle; -import java.util.logging.Logger; + +import static java.text.MessageFormat.format; public class SBMLPolisher extends AbstractPolisher { - private static final Logger logger = Logger.getLogger(SBMLPolisher.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SBMLPolisher.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private final SBOParameters sboParameters; @@ -40,9 +43,10 @@ public SBMLPolisher(PolishingParameters parameters, SBOParameters sboParameters, */ @Override public void polish(SBMLDocument doc) { + logger.debug(format("Polish doc: {0}", doc.toString())); // Ensure the document is at the correct SBML level and version if (!doc.isSetLevelAndVersion() || (doc.getLevelAndVersion().compareTo(ValuePair.of(3, 1)) < 0)) { - logger.info(MESSAGES.getString("TRY_CONV_LVL3_V1")); + logger.debug(MESSAGES.getString("TRY_CONV_LVL3_V1")); SBMLtools.setLevelAndVersion(doc, 3, 1); } @@ -55,6 +59,7 @@ public void polish(SBMLDocument doc) { new ModelPolisher(polishingParameters, sboParameters, registry, getObservers()).polish(model); // Process any external resources linked in the document's annotations. + diffReport("documentAnnotation", doc.getAnnotation().clone(), doc.getAnnotation()); new AnnotationPolisher(polishingParameters, registry).polish(doc.getAnnotation()); } diff --git a/src/main/java/edu/ucsd/sbrg/polishing/SpeciesPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/SpeciesPolisher.java index 8970f070..0bb19b9c 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/SpeciesPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/SpeciesPolisher.java @@ -6,12 +6,13 @@ import edu.ucsd.sbrg.reporting.ProgressObserver; import edu.ucsd.sbrg.resolver.Registry; import org.sbml.jsbml.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.ResourceBundle; -import java.util.logging.Logger; import static java.text.MessageFormat.format; @@ -22,8 +23,7 @@ */ public class SpeciesPolisher extends AbstractPolisher { - private static final Logger logger = Logger.getLogger(SpeciesPolisher.class.getName()); - + private static final Logger logger = LoggerFactory.getLogger(SpeciesPolisher.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); private final List speciesToRemove = new ArrayList<>(); @@ -44,8 +44,10 @@ public SpeciesPolisher(PolishingParameters parameters, Registry registry, List

species) { + logger.debug("Polish Species"); for (Species s : species) { statusReport("Polishing Species (4/9) ", s); // Update progress display for each species + diffReport("species", s.clone(), s); // Polish each species and collect those that need to be removed polish(s); } @@ -66,9 +68,9 @@ public void polish(Species species) { // Check if the species ID is missing and log an error if so if (id.isEmpty()) { if (species.isSetName()) { - logger.severe(format(MESSAGES.getString("SPECIES_MISSING_ID"), species.getName())); + logger.info(format(MESSAGES.getString("SPECIES_MISSING_ID"), species.getName())); } else { - logger.severe(MESSAGES.getString("SPECIES_MISSING_ID_NAME")); + logger.info(MESSAGES.getString("SPECIES_MISSING_ID_NAME")); } speciesToRemove.add(species); return; @@ -76,9 +78,9 @@ public void polish(Species species) { // Warn if the species ID indicates a boundary species but the boundary condition is not set if (species.getId().endsWith("_boundary")) { - logger.warning(format(MESSAGES.getString("SPECIES_ID_INVALID"), id)); + logger.info(format(MESSAGES.getString("SPECIES_ID_INVALID"), id)); if (!species.isSetBoundaryCondition() || !species.isBoundaryCondition()) { - logger.warning(format(MESSAGES.getString("BOUNDARY_FLAG_MISSING"), id)); + logger.info(format(MESSAGES.getString("BOUNDARY_FLAG_MISSING"), id)); species.setBoundaryCondition(true); } } else if (!species.isSetBoundaryCondition()) { @@ -100,7 +102,7 @@ public void polish(Species species) { BiGGId.createMetaboliteId(id).ifPresent(biggId -> { if (biggId.isSetCompartmentCode() && species.isSetCompartment() && !biggId.getCompartmentCode().equals(species.getCompartment())) { - logger.warning(format(MESSAGES.getString("CHANGE_COMPART_REFERENCE"), species.getId(), species.getCompartment(), + logger.info(format(MESSAGES.getString("CHANGE_COMPART_REFERENCE"), species.getId(), species.getCompartment(), biggId.getCompartmentCode())); species.setCompartment(biggId.getCompartmentCode()); } @@ -152,7 +154,7 @@ public void checkCompartment(Species species) { compartmentPolisher.polish((Compartment) candidate); } else if (candidate == null) { // If no compartment is found, log a warning and create a new compartment - logger.warning(format(MESSAGES.getString("CREATE_MISSING_COMP"), cId, species.getId(), species.getElementName())); + logger.info(format(MESSAGES.getString("CREATE_MISSING_COMP"), cId, species.getId(), species.getElementName())); var compartmentPolisher = new CompartmentPolisher(polishingParameters, registry, getObservers()); compartmentPolisher.polish(model.createCompartment(cId)); } diff --git a/src/main/java/edu/ucsd/sbrg/polishing/UnitPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/UnitPolisher.java index d265f2c3..7444a616 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/UnitPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/UnitPolisher.java @@ -6,10 +6,14 @@ import edu.ucsd.sbrg.reporting.ProgressObserver; import org.sbml.jsbml.*; import org.sbml.jsbml.util.ModelBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.Optional; +import static java.text.MessageFormat.format; + /** * This class is responsible for ensuring that all necessary {@link UnitDefinition}s and {@link Unit}s are correctly * defined and present in the SBML model. It handles the creation and verification of units used in the model, @@ -36,6 +40,7 @@ public class UnitPolisher extends AbstractPolisher{ public static final CVTerm CV_TERM_IS_UO_GRAM = new CVTerm(CVTerm.Qualifier.BQB_IS, new IdentifiersOrgURI("unit", "UO:0000021").getURI()); public static final CVTerm CV_TERM_IS_VERSION_OF_UO_SECOND = new CVTerm(CVTerm.Qualifier.BQB_IS_VERSION_OF, new IdentifiersOrgURI("unit", "UO:0000010").getURI()); public static final CVTerm CV_TERM_IS_VERSION_OF_UO_MOLE = new CVTerm(CVTerm.Qualifier.BQB_IS_VERSION_OF, new IdentifiersOrgURI("unit", "UO:0000013").getURI()); + private static final Logger logger = LoggerFactory.getLogger(UnitPolisher.class); public UnitPolisher(PolishingParameters parameters, Registry registry) { super(parameters, registry); @@ -50,13 +55,12 @@ public UnitPolisher(PolishingParameters parameters, Registry registry, List findGrowthUnit(ListOf uds, UnitDefinition growth) { + private Optional findEquivalentGrowthUnit(ListOf uds, UnitDefinition growth) { return uds.stream().filter(u -> UnitDefinition.areEquivalent(u, growth)).findFirst(); } @@ -110,23 +115,25 @@ private UnitDefinition defaultGrowthUnitDefinition(Model model) { * @return The newly created or modified growth unit definition. */ private UnitDefinition createGrowthUnitDefinition(Model model) { - // Create a default growth unit definition. var growth = defaultGrowthUnitDefinition(model); - // Check if an equivalent growth unit already exists in the model. - var otherGrowth = findGrowthUnit(model.getListOfUnitDefinitions(), growth).orElse(growth); - // Set the meta ID of the growth unit if it is not already set. - if (!growth.isSetMetaId()) - growth.setMetaId(growth.getId()); - // Annotate the growth unit definition with relevant metadata. - annotateGrowthUnitDefinition(growth); - // If the found growth unit is the same as the newly created one and it already exists in the model, - // change its ID to indicate that it was preexisting. - if (otherGrowth.equals(growth) && null != model.getUnitDefinition(GROWTH_UNIT_ID)) { - model.getUnitDefinition(GROWTH_UNIT_ID).setId(GROWTH_UNIT_ID + "__preexisting"); + var otherGrowth = findEquivalentGrowthUnit(model.getListOfUnitDefinitions(), growth); + + if (otherGrowth.isPresent()) { + if (!otherGrowth.get().isSetMetaId()) + otherGrowth.get().setMetaId(growth.getId()); + annotateGrowthUnitDefinition(otherGrowth.get()); + otherGrowth.get().setId(GROWTH_UNIT_ID); + return otherGrowth.get(); + } else { + if (!growth.isSetMetaId()) + growth.setMetaId(growth.getId()); + annotateGrowthUnitDefinition(growth); + if (null != model.getUnitDefinition(GROWTH_UNIT_ID)) { + model.getUnitDefinition(GROWTH_UNIT_ID).setId(GROWTH_UNIT_ID + "__preexisting"); + } + model.addUnitDefinition(growth); + return growth; } - // Add the growth unit definition to the model. - model.addUnitDefinition(growth); - return growth; } private CVTerm genericUnitAnnotation(Unit u) { diff --git a/src/main/java/edu/ucsd/sbrg/polishing/fbc/FBCPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/fbc/FBCPolisher.java index b3760cc9..db93ad5c 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/fbc/FBCPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/fbc/FBCPolisher.java @@ -3,22 +3,24 @@ import de.zbit.util.ResourceManager; import edu.ucsd.sbrg.polishing.AbstractPolisher; import edu.ucsd.sbrg.parameters.PolishingParameters; +import edu.ucsd.sbrg.polishing.ReactionsPolisher; import edu.ucsd.sbrg.polishing.SBMLPolisher; import edu.ucsd.sbrg.reporting.ProgressObserver; import edu.ucsd.sbrg.resolver.Registry; import org.sbml.jsbml.Model; import org.sbml.jsbml.ext.fbc.FBCConstants; import org.sbml.jsbml.ext.fbc.FBCModelPlugin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.ResourceBundle; -import java.util.logging.Logger; import static java.text.MessageFormat.format; public class FBCPolisher extends AbstractPolisher { - private static final Logger logger = Logger.getLogger(SBMLPolisher.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(FBCPolisher.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); public FBCPolisher(PolishingParameters parameters, Registry registry, List observers) { @@ -27,6 +29,7 @@ public FBCPolisher(PolishingParameters parameters, Registry registry, List { + private static final Logger logger = LoggerFactory.getLogger(FluxObjectivesPolisher.class); private final FBCModelPlugin modelPlug; @@ -34,7 +37,10 @@ public FluxObjectivesPolisher(FBCModelPlugin modelPlug, PolishingParameters para */ @Override public void polish(List objectives) { + logger.debug("Polish Objectives"); + for (var objective : objectives) { + diffReport("objective", objective.clone(), objective); statusReport("Polishing Objectives (7/9) ", objective); // "Processing objective " + objective.getId()); if (!objective.isSetListOfFluxObjectives() || objective.getListOfFluxObjectives().isEmpty()) { var model = objective.getModel(); diff --git a/src/main/java/edu/ucsd/sbrg/polishing/fbc/GeneProductsPolisher.java b/src/main/java/edu/ucsd/sbrg/polishing/fbc/GeneProductsPolisher.java index 91c9033e..ab89a1e4 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/fbc/GeneProductsPolisher.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/fbc/GeneProductsPolisher.java @@ -8,6 +8,8 @@ import org.sbml.jsbml.ext.fbc.GeneProduct; import edu.ucsd.sbrg.db.bigg.BiGGId; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; @@ -15,7 +17,7 @@ * This class is responsible for polishing GeneProduct instances by processing their annotations and adjusting their identifiers and names. */ public class GeneProductsPolisher extends AbstractPolisher { - + private static final Logger logger = LoggerFactory.getLogger(GeneProductsPolisher.class); public GeneProductsPolisher(PolishingParameters parameters, Registry registry, List observers) { super(parameters, registry, observers); @@ -24,8 +26,11 @@ public GeneProductsPolisher(PolishingParameters parameters, Registry registry, L @Override public void polish(List geneProducts) { + logger.debug("Polish Gene Products"); + for (GeneProduct geneProduct : geneProducts) { statusReport("Polishing Gene Products (8/9) ", geneProduct); + diffReport("geneProduct", geneProduct.clone(), geneProduct); polish(geneProduct); } } @@ -49,6 +54,7 @@ public void polish(GeneProduct geneProduct) { } private void setName(GeneProduct geneProduct) { + String label = null; // Determine the label from the gene product's label or ID if (geneProduct.isSetLabel() && !geneProduct.getLabel().equalsIgnoreCase("None")) { diff --git a/src/main/java/edu/ucsd/sbrg/polishing/fbc/StrictnessPredicate.java b/src/main/java/edu/ucsd/sbrg/polishing/fbc/StrictnessPredicate.java index 5cb2de95..12fefafd 100644 --- a/src/main/java/edu/ucsd/sbrg/polishing/fbc/StrictnessPredicate.java +++ b/src/main/java/edu/ucsd/sbrg/polishing/fbc/StrictnessPredicate.java @@ -2,6 +2,8 @@ import org.sbml.jsbml.*; import org.sbml.jsbml.ext.fbc.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.function.Predicate; @@ -38,9 +40,12 @@ * (implemented via {@link #reactionHasValidBounds}) */ public class StrictnessPredicate implements Predicate { + private static final Logger logger = LoggerFactory.getLogger(StrictnessPredicate.class); @Override public boolean test(Model model) { + logger.debug("Test Strictness"); + var strict = model.getListOfReactions().stream() .allMatch(reaction -> reactionHasValidBounds(reaction) diff --git a/src/main/java/edu/ucsd/sbrg/reporting/PolisherProgressBar.java b/src/main/java/edu/ucsd/sbrg/reporting/PolisherProgressBar.java index 9a447b37..c25b29ab 100644 --- a/src/main/java/edu/ucsd/sbrg/reporting/PolisherProgressBar.java +++ b/src/main/java/edu/ucsd/sbrg/reporting/PolisherProgressBar.java @@ -13,7 +13,8 @@ public void initialize(ProgressInitialization init) { @Override public void update(ProgressUpdate update) { - bar.DisplayBar(update.text()); + if(update.reportType().equals(ReportType.STATUS)) + bar.DisplayBar(update.text()); } @Override diff --git a/src/main/java/edu/ucsd/sbrg/reporting/ProgressUpdate.java b/src/main/java/edu/ucsd/sbrg/reporting/ProgressUpdate.java index 336e5fba..83b5a94a 100644 --- a/src/main/java/edu/ucsd/sbrg/reporting/ProgressUpdate.java +++ b/src/main/java/edu/ucsd/sbrg/reporting/ProgressUpdate.java @@ -1,5 +1,5 @@ package edu.ucsd.sbrg.reporting; -public record ProgressUpdate(String text, Object obj, ReportType status) { +public record ProgressUpdate(String text, Object obj, ReportType reportType) { } diff --git a/src/main/java/edu/ucsd/sbrg/reporting/ReportType.java b/src/main/java/edu/ucsd/sbrg/reporting/ReportType.java index f07c8790..51b142f8 100644 --- a/src/main/java/edu/ucsd/sbrg/reporting/ReportType.java +++ b/src/main/java/edu/ucsd/sbrg/reporting/ReportType.java @@ -1,5 +1,5 @@ package edu.ucsd.sbrg.reporting; public enum ReportType { - STATUS + DATA, STATUS } diff --git a/src/main/java/edu/ucsd/sbrg/util/GPRParser.java b/src/main/java/edu/ucsd/sbrg/util/GPRParser.java index af00d5a1..ac97a1f1 100644 --- a/src/main/java/edu/ucsd/sbrg/util/GPRParser.java +++ b/src/main/java/edu/ucsd/sbrg/util/GPRParser.java @@ -7,6 +7,7 @@ import java.util.Set; import java.util.logging.Logger; +import edu.ucsd.sbrg.io.parsers.cobra.MatlabParser; import org.sbml.jsbml.*; import org.sbml.jsbml.ext.fbc.And; import org.sbml.jsbml.ext.fbc.Association; @@ -23,6 +24,7 @@ import de.zbit.util.ResourceManager; import de.zbit.util.Utils; import edu.ucsd.sbrg.db.bigg.BiGGId; +import org.slf4j.LoggerFactory; import static java.text.MessageFormat.format; @@ -42,13 +44,7 @@ */ public class GPRParser { - /** - * A {@link Logger} for this class. - */ - private static final Logger logger = Logger.getLogger(GPRParser.class.getName()); - /** - * Bundle for ModelPolisher logger messages - */ + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(GPRParser.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); @@ -70,7 +66,7 @@ public static void parseGPR(Reaction r, String geneReactionRule, boolean omitGen convertToAssociation(ASTNode.parseFormula(geneReactionRule, new CobraFormulaParser(new StringReader(""))), r.getId(), r.getModel(), omitGenericTerms); } catch (Throwable exc) { - logger.warning(format(MESSAGES.getString("PARSE_GPR_ERROR"), geneReactionRule, Utils.getMessage(exc))); + logger.info(format(MESSAGES.getString("PARSE_GPR_ERROR"), geneReactionRule, Utils.getMessage(exc))); } if (association != null) { parseGPR(r, association, omitGenericTerms); @@ -157,7 +153,7 @@ public static GeneProductRef createGPR(String identifier, String reactionId, Mod } // If the GeneProduct does not exist, create a new one and log a warning. if (gp == null) { - logger.warning(format(MESSAGES.getString("CREATE_MISSING_GPR"), id, reactionId)); + logger.info(format(MESSAGES.getString("CREATE_MISSING_GPR"), id, reactionId)); FBCModelPlugin fbcPlug = (FBCModelPlugin) model.getPlugin(FBCConstants.shortLabel); gp = fbcPlug.createGeneProduct(id); gp.setLabel(id); @@ -290,7 +286,7 @@ private static void mergeAssociation(Reaction r, Association association, FBCRea String geneProduct = ((GeneProductRef) current).getGeneProduct(); if (gprs.contains(geneProduct)) { if (!or.removeAssociation(current)) { - logger.warning(format("Failed to unset duplicate GeneProductReference {0} for reaction {1}", + logger.info(format("Failed to unset duplicate GeneProductReference {0} for reaction {1}", geneProduct, r.getId())); } } else { diff --git a/src/main/java/edu/ucsd/sbrg/util/SBMLFix.java b/src/main/java/edu/ucsd/sbrg/util/SBMLFix.java index a0dfa564..ef57ae01 100644 --- a/src/main/java/edu/ucsd/sbrg/util/SBMLFix.java +++ b/src/main/java/edu/ucsd/sbrg/util/SBMLFix.java @@ -9,6 +9,7 @@ import de.zbit.util.Utils; import de.zbit.util.logging.LogUtil; import edu.ucsd.sbrg.ModelPolisherCLILauncher; +import edu.ucsd.sbrg.io.ModelWriter; import edu.ucsd.sbrg.polishing.ReactionNamePatterns; import org.sbml.jsbml.ListOf; import org.sbml.jsbml.Model; @@ -22,6 +23,7 @@ import org.sbml.jsbml.ext.groups.Group; import org.sbml.jsbml.ext.groups.GroupsConstants; import org.sbml.jsbml.ext.groups.GroupsModelPlugin; +import org.slf4j.LoggerFactory; import javax.xml.stream.XMLStreamException; import java.io.File; @@ -52,21 +54,10 @@ */ public class SBMLFix { - /** - * A {@link Logger} for this class. - */ - private static final Logger logger = Logger.getLogger(SBMLFix.class.getName()); - /** - * Bundle for ModelPolisher logger messages - */ + private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SBMLFix.class); private static final ResourceBundle MESSAGES = ResourceManager.getBundle("edu.ucsd.sbrg.polisher.Messages"); - /** - * - */ private static final double DEFAULT_COEFFICIENT = 1d; - /** - */ public static void batchProcess(File input, File output) { if (!output.exists() && !output.isFile() && !(input.isFile() && input.getName().equals(output.getName()))) { logger.info(MessageFormat.format(MESSAGES.getString("DIRECTORY_CREATED"), output.getAbsolutePath())); @@ -81,12 +72,12 @@ public static void batchProcess(File input, File output) { try { fixSBML(input, output); } catch (XMLStreamException | IOException exc) { - logger.severe(exc.getMessage()); + logger.error(exc.getMessage()); } } } else { if (!output.isDirectory()) { - logger.severe(MessageFormat.format(MESSAGES.getString("WRITE_TO_FILE_ERROR"), output.getAbsolutePath())); + logger.error(MessageFormat.format(MESSAGES.getString("WRITE_TO_FILE_ERROR"), output.getAbsolutePath())); } for (File file : input.listFiles()) { File target = new File(Utils.ensureSlash(output.getAbsolutePath()) + file.getName()); @@ -143,7 +134,7 @@ public static void fixObjective(String modelDescriptor, ListOf listOfR List fluxCoefficients, List fluxObjectives) { Objective activeObjective = null; if (!fbcPlug.isSetActiveObjective()) { - logger.severe(MessageFormat.format(MESSAGES.getString("OBJ_NOT_DEFINED"), modelDescriptor)); + logger.info(MessageFormat.format(MESSAGES.getString("OBJ_NOT_DEFINED"), modelDescriptor)); if (fbcPlug.getObjectiveCount() == 1) { activeObjective = fbcPlug.getObjective(0); fbcPlug.setActiveObjective(activeObjective); @@ -154,7 +145,7 @@ public static void fixObjective(String modelDescriptor, ListOf listOfR } if (activeObjective != null) { if (!activeObjective.isSetListOfFluxObjectives()) { - logger.severe(MessageFormat.format(MESSAGES.getString("TRY_GUESS_MISSING_FLUX_OBJ"), modelDescriptor)); + logger.info(MessageFormat.format(MESSAGES.getString("TRY_GUESS_MISSING_FLUX_OBJ"), modelDescriptor)); if (listOfReactions != null) { if (fluxObjectives != null && !fluxObjectives.isEmpty()) { /* @@ -168,7 +159,7 @@ public static void fixObjective(String modelDescriptor, ListOf listOfR if (r != null) { createFluxObjective(modelDescriptor, r, fluxCoefficients, activeObjective, i); } else { - logger.severe(MessageFormat.format(MESSAGES.getString("REACTION_UNKNOWN_ERROR"), id, modelDescriptor)); + logger.info(MessageFormat.format(MESSAGES.getString("REACTION_UNKNOWN_ERROR"), id, modelDescriptor)); } } } else { @@ -182,11 +173,11 @@ public static void fixObjective(String modelDescriptor, ListOf listOfR if (rBiomass != null) { createFluxObjective(modelDescriptor, rBiomass, fluxCoefficients, activeObjective, 0); } else { - logger.severe(MESSAGES.getString("REACTION_BIOMASS_UNKNOWN_ERROR")); + logger.info(MESSAGES.getString("REACTION_BIOMASS_UNKNOWN_ERROR")); } } } else { - logger.severe(MessageFormat.format(MESSAGES.getString("REACTION_LIST_MISSING"), modelDescriptor)); + logger.info(MessageFormat.format(MESSAGES.getString("REACTION_LIST_MISSING"), modelDescriptor)); } } } diff --git a/src/test/java/edu/ucsd/sbrg/TestUtils.java b/src/test/java/edu/ucsd/sbrg/TestUtils.java index 33dfb8dd..d3bbf5ec 100644 --- a/src/test/java/edu/ucsd/sbrg/TestUtils.java +++ b/src/test/java/edu/ucsd/sbrg/TestUtils.java @@ -1,6 +1,5 @@ package edu.ucsd.sbrg; -import edu.ucsd.sbrg.parameters.OutputParameters; import org.sbml.jsbml.AbstractNamedSBase; import org.sbml.jsbml.AbstractSBase; import org.sbml.jsbml.CVTerm; diff --git a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotatorTest.java b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotatorTest.java index f685abf8..30e90c46 100644 --- a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotatorTest.java +++ b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGCompartmentsAnnotatorTest.java @@ -7,6 +7,7 @@ import org.sbml.jsbml.Compartment; import org.sbml.jsbml.SBO; +import java.sql.SQLException; import java.util.Map; import static edu.ucsd.sbrg.TestUtils.*; @@ -17,7 +18,7 @@ public class BiGGCompartmentsAnnotatorTest extends BiGGDBContainerTest { private final BiGGAnnotationParameters parameters = new BiGGAnnotationParameters(); @Test - public void annotateKnownCompartments() { + public void annotateKnownCompartments() throws SQLException { for (var c_id : bigg.getAllBiggIds("compartment")) { var c = new Compartment(c_id,3, 2); @@ -39,7 +40,7 @@ public void annotateKnownCompartments() { } @Test - public void nameAnnotationIsSane() { + public void nameAnnotationIsSane() throws SQLException { var c = new Compartment("im", "default",3, 2); new BiGGCompartmentsAnnotator(bigg, parameters, new IdentifiersOrg()).annotate(c); diff --git a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotatorTest.java b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotatorTest.java index 081fd200..045f9daf 100644 --- a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotatorTest.java +++ b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGModelAnnotatorTest.java @@ -6,6 +6,8 @@ import org.sbml.jsbml.CVTerm; import org.sbml.jsbml.Model; +import java.sql.SQLException; + import static edu.ucsd.sbrg.TestUtils.assertCVTermIsPresent; import static org.junit.jupiter.api.Assertions.*; @@ -20,7 +22,7 @@ public class BiGGModelAnnotatorTest extends BiGGDBContainerTest { ); @Test - public void basicModelAnnotation() { + public void basicModelAnnotation() throws SQLException { var m = new Model("iJO1366", 3,2); assertFalse(m.isSetMetaId()); diff --git a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotatorTest.java b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotatorTest.java index ca0817c8..b6b5c0f4 100644 --- a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotatorTest.java +++ b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGReactionsAnnotatorTest.java @@ -17,6 +17,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; +import java.sql.SQLException; import java.util.Set; import java.util.stream.Collectors; @@ -38,7 +39,7 @@ public BiGGReactionsAnnotatorTest() throws IOException { } @Test - public void getBiGGIdFromResourcesTest() { + public void getBiGGIdFromResourcesTest() throws SQLException { var m = new Model("iJO1366", 3, 2); var r1 = m.createReaction("some_name"); var r2 = m.createReaction("some_other_name"); diff --git a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotatorTest.java b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotatorTest.java index 09cfdf03..399aa03d 100644 --- a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotatorTest.java +++ b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSBMLAnnotatorTest.java @@ -1,6 +1,7 @@ package edu.ucsd.sbrg.annotation.bigg; import edu.ucsd.sbrg.ModelPolisherOptions; +import edu.ucsd.sbrg.annotation.AnnotationException; import edu.ucsd.sbrg.parameters.BiGGAnnotationParameters; import edu.ucsd.sbrg.parameters.BiGGNotesParameters; import edu.ucsd.sbrg.parameters.SBOParameters; @@ -10,6 +11,8 @@ import org.sbml.jsbml.Model; import org.sbml.jsbml.SBMLDocument; +import java.sql.SQLException; + import static edu.ucsd.sbrg.TestUtils.assertCVTermIsPresent; import static org.junit.jupiter.api.Assertions.*; @@ -25,7 +28,7 @@ public class BiGGSBMLAnnotatorTest extends BiGGDBContainerTest { private final SBOParameters sboParameters = new SBOParameters(); @Test - public void annotatePublication() { + public void annotatePublication() throws SQLException, AnnotationException { var sbml = new SBMLDocument(3, 2); var m = new Model("iJO1366", 3, 2); diff --git a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotatorTest.java b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotatorTest.java index df4ba56d..fe5616b8 100644 --- a/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotatorTest.java +++ b/src/test/java/edu/ucsd/sbrg/annotation/bigg/BiGGSpeciesAnnotatorTest.java @@ -9,6 +9,7 @@ import org.sbml.jsbml.ext.fbc.FBCConstants; import org.sbml.jsbml.ext.fbc.FBCSpeciesPlugin; +import java.sql.SQLException; import java.util.Map; import java.util.Set; @@ -22,7 +23,7 @@ public class BiGGSpeciesAnnotatorTest extends BiGGDBContainerTest { private final SBOParameters sboParameters = new SBOParameters(); @Test - public void basicAnnotationTest() { + public void basicAnnotationTest() throws SQLException { var m = new Model(3, 2); var s = m.createSpecies("atp"); var sFbcPlugin = (FBCSpeciesPlugin) s.getPlugin(FBCConstants.shortLabel); @@ -40,7 +41,7 @@ public void basicAnnotationTest() { } @Test - public void unknownMetaboliteCanBeInferredFromId() { + public void unknownMetaboliteCanBeInferredFromId() throws SQLException { var m = new Model(3, 2); var s = m.createSpecies("atp_c"); @@ -57,7 +58,7 @@ public void unknownMetaboliteCanBeInferredFromId() { } @Test - public void unknownMetaboliteCanBeInferredFromCV() { + public void unknownMetaboliteCanBeInferredFromCV() throws SQLException { var m = new Model(3, 2); var s = m.createSpecies("big_chungus"); @@ -122,7 +123,7 @@ public void unknownMetaboliteCanBeInferredFromCV() { * The annotations as are should likely not be considered correct. */ @Test - public void H2OAnnotationTest() { + public void H2OAnnotationTest() throws SQLException { var m = new Model(3, 2); var s = m.createSpecies("h2o"); var sFbcPlugin = (FBCSpeciesPlugin) s.getPlugin(FBCConstants.shortLabel); @@ -195,7 +196,7 @@ public void H2OAnnotationTest() { * Same principle as above, just testing for kegg and biocyc too. */ @Test - public void getBiGGIdFromResourcesTest() { + public void getBiGGIdFromResourcesTest() throws SQLException { var m = new Model("iJO1366", 3, 2); var s1 = m.createSpecies("some_name"); var s2 = m.createSpecies("some_other_name"); diff --git a/src/test/java/edu/ucsd/sbrg/db/bigg/BiGGDBTest.java b/src/test/java/edu/ucsd/sbrg/db/bigg/BiGGDBTest.java index 9d525f6d..f4b46a4d 100644 --- a/src/test/java/edu/ucsd/sbrg/db/bigg/BiGGDBTest.java +++ b/src/test/java/edu/ucsd/sbrg/db/bigg/BiGGDBTest.java @@ -4,6 +4,7 @@ import org.junit.jupiter.api.Test; import org.testcontainers.junit.jupiter.Testcontainers; +import java.sql.SQLException; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -14,7 +15,7 @@ public class BiGGDBTest extends BiGGDBContainerTest { @Test - public void getSubsystems() { + public void getSubsystems() throws SQLException { var org = bigg.getOrganism("iJO1366"); assertTrue(org.isPresent()); assertEquals("Escherichia coli str. K-12 substr. MG1655", org.get()); @@ -22,11 +23,11 @@ public void getSubsystems() { /** - * This test serves primarily as documentation and to to raise awareness for + * This test serves primarily as documentation and to raise awareness for * new data sources in case of DB update. */ @Test - public void dataSources() { + public void dataSources() throws SQLException { var dataSources = bigg.getAllBiggIds("data_source"); assertEquals(Set.of("asap", "biocyc", diff --git a/src/test/java/edu/ucsd/sbrg/parameters/ParametersParserTest.java b/src/test/java/edu/ucsd/sbrg/parameters/ParametersParserTest.java index 2ddc963b..ce4bffa0 100644 --- a/src/test/java/edu/ucsd/sbrg/parameters/ParametersParserTest.java +++ b/src/test/java/edu/ucsd/sbrg/parameters/ParametersParserTest.java @@ -3,7 +3,6 @@ import edu.ucsd.sbrg.ModelPolisherOptions; import edu.ucsd.sbrg.db.adb.AnnotateDBOptions; import edu.ucsd.sbrg.db.bigg.BiGGDBOptions; -import edu.ucsd.sbrg.io.IOOptions; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; @@ -66,10 +65,7 @@ void defaults() throws IOException { assertEquals(BiGGDBOptions.PASSWD.getDefaultValue(), parameters.annotation().biggAnnotationParameters().dbParameters().passwd()); - assertEquals(IOOptions.OUTPUT.getDefaultValue(), parameters.output().outputFile()); - assertEquals(ModelPolisherOptions.OUTPUT_COMBINE.getDefaultValue(), parameters.output().outputCOMBINE()); - assertEquals(ModelPolisherOptions.WRITE_JSON.getDefaultValue(), parameters.output().writeJSON()); - assertEquals(ModelPolisherOptions.COMPRESSION_TYPE.getDefaultValue(), parameters.output().compression()); + assertEquals(ModelPolisherOptions.OUTPUT_TYPE.getDefaultValue(), parameters.outputType()); } @Test @@ -77,6 +73,6 @@ void parse() throws IOException { var parameters = new ParametersParser() .parse(ParametersParserTest.class.getResourceAsStream("parameters.json")); assertNotNull(parameters); - assertEquals(ModelPolisherOptions.Compression.ZIP, parameters.output().compression()); + assertEquals(ModelPolisherOptions.OutputType.COMBINE, parameters.outputType()); } } \ No newline at end of file diff --git a/src/test/resources/edu/ucsd/sbrg/parameters/parameters.json b/src/test/resources/edu/ucsd/sbrg/parameters/parameters.json index 810bc16a..caa225b3 100644 --- a/src/test/resources/edu/ucsd/sbrg/parameters/parameters.json +++ b/src/test/resources/edu/ucsd/sbrg/parameters/parameters.json @@ -39,9 +39,5 @@ } } }, - "output": { - "write-json": false, - "output-combine": false, - "compression": "zip" - } + "outputType": "combine" } \ No newline at end of file