001package org.biojava.nbio.structure.chem;
002
003import org.biojava.nbio.structure.io.cif.ChemCompConsumer;
004import org.biojava.nbio.structure.io.cif.ChemCompConsumerImpl;
005import org.biojava.nbio.structure.io.cif.ChemCompConverter;
006import org.slf4j.Logger;
007import org.slf4j.LoggerFactory;
008
009import java.io.BufferedReader;
010import java.io.IOException;
011import java.io.InputStream;
012import java.io.InputStreamReader;
013import java.util.zip.GZIPInputStream;
014
015/**
016 * Unlike the {@link DownloadChemCompProvider}, this  {@link ChemCompProvider} does not download any chem comp
017 * definitions. It has access to a limited set of files that are part of the biojava distribution.
018 *
019 * @author Andreas Prlic
020 * @since 3.0
021 */
022public class ReducedChemCompProvider implements ChemCompProvider {
023    private static final Logger logger = LoggerFactory.getLogger(ReducedChemCompProvider.class);
024
025    public ReducedChemCompProvider(){
026        logger.debug("Initialising ReducedChemCompProvider");
027    }
028
029    @Override
030    public ChemComp getChemComp(String recordName) {
031        String name = recordName.toUpperCase().trim();
032        try (InputStream inStream = this.getClass().getResourceAsStream("/chemcomp/" + name + ".cif.gz")) {
033            logger.debug("Reading chemcomp/{}.cif.gz", recordName);
034
035            if (inStream == null) {
036                //System.out.println("Could not find chem comp: " + name + " ... using generic Chem Comp");
037                // could not find the chem comp definition for this in the jar file
038                logger.debug("Getting empty chem comp for {}", name);
039                ChemComp cc = ChemComp.getEmptyChemComp();
040                cc.setId(name);
041                return cc;
042            }
043
044            // The Consumer builds up the BioJava - structure object.
045            // you could also hook in your own and build up you own data model.
046            ChemicalComponentDictionary dict = ChemCompConverter.fromInputStream(inStream);
047
048            return dict.getChemComp(name);
049        } catch (IOException e) {
050            logger.error("IOException caught while reading chem comp {}.", name, e);
051        }
052        logger.warn("Problem when loading chem comp {}, will use an empty chem comp for it", name);
053        ChemComp cc = ChemComp.getEmptyChemComp();
054        cc.setId(name);
055        return cc;
056    }
057}
058