Exemple #1
0
 /// <summary> Creates a new IChemObjectReader based on the given IChemFormat.
 ///
 /// </summary>
 /// <seealso cref="createReader(InputStream)">
 /// </seealso>
 public virtual IChemObjectReader createReader(IChemFormat format)
 {
     if (format != null)
     {
         System.String readerClassName = format.ReaderClassName;
         if (readerClassName != null)
         {
             try
             {
                 // make a new instance of this class
                 ObjectHandle handle = System.Activator.CreateInstance("NuGenCDKSharp", readerClassName);
                 return((IChemObjectReader)handle.Unwrap());
             }
             catch (System.Exception exception)
             {
                 //logger.error("Could not find this ChemObjectReader: ", readerClassName);
                 //logger.debug(exception);
             }
         }
         else
         {
             // TODO: HAndle no reader available
             //logger.warn("ChemFormat is recognized, but no reader is available.");
         }
     }
     else
     {
         //logger.warn("ChemFormat is not recognized.");
     }
     return(null);
 }
        /// <summary>
        /// Method will return an appropriate reader for the provided format. Each reader is stored
        /// in a map, if no reader is available for the specified format a new reader is created. The
        /// <see cref="IChemObjectReader.ErrorHandler"/> and
        /// <see cref="IChemObjectReader.ReaderMode"/> are set.
        /// </summary>
        /// <param name="format">The format to obtain a reader for</param>
        /// <returns>instance of a reader appropriate for the provided format</returns>
        private ISimpleChemObjectReader GetReader(IChemFormat format, TextReader input)
        {
            ISimpleChemObjectReader reader;

            if (format is MDLV2000Format)
            {
                reader = new MDLV2000Reader(input);
            }
            else if (format is MDLV3000Format)
            {
                reader = new MDLV3000Reader(input);
            }
            else if (format is MDLFormat)
            {
                reader = new MDLReader(input);
            }
            else
            {
                throw new ArgumentException("Unexpected format: " + format);
            }
            reader.ErrorHandler = this.ErrorHandler;
            reader.ReaderMode   = this.ReaderMode;
            if (currentFormat is MDLV2000Format)
            {
                reader.AddSettings(IOSettings.Settings);
            }

            return(reader);
        }
        /// <summary>
        /// Method will return an appropriate reader for the provided format. Each reader is stored
        /// in a map, if no reader is available for the specified format a new reader is created. The
        /// <see cref="IChemObjectReader.ErrorHandler"/> and
        /// <see cref="IChemObjectReader.ReaderMode"/> are set.
        /// </summary>
        /// <param name="format">The format to obtain a reader for</param>
        /// <returns>instance of a reader appropriate for the provided format</returns>
        private ISimpleChemObjectReader GetReader(IChemFormat format, TextReader input)
        {
            ISimpleChemObjectReader reader;

            switch (format)
            {
            case MDLV2000Format _:
                reader = new MDLV2000Reader(input);
                break;

            case MDLV3000Format _:
                reader = new MDLV3000Reader(input);
                break;

            case MDLFormat _:
                reader = new MDLReader(input);
                break;

            default:
                throw new ArgumentException($"Unexpected format: {format}");
            }
            reader.ErrorHandler = this.ErrorHandler;
            reader.ReaderMode   = this.ReaderMode;
            if (currentFormat is MDLV2000Format)
            {
                reader.AddSettings(IOSettings.Settings);
            }

            return(reader);
        }
        public void TestCreateReader_IChemFormat()
        {
            IChemFormat             format = (IChemFormat)XYZFormat.Instance;
            ISimpleChemObjectReader reader = factory.CreateReader(format, new StringReader(""));

            Assert.IsNotNull(reader);
            Assert.AreEqual(format.FormatName, reader.Format.FormatName);
        }
        public void TestCreateWriter_IChemFormat()
        {
            IChemFormat       format = (IChemFormat)XYZFormat.Instance;
            IChemObjectWriter writer = factory.CreateWriter(format, new StringWriter());

            Assert.IsNotNull(writer);
            Assert.AreEqual(format.FormatName, writer.Format.FormatName);
        }
Exemple #6
0
        /// <summary>
        /// Detects the format of the Reader input, and if known, it will return
        /// a CDK Reader to read the format, or null when the reader is not
        /// implemented.
        /// </summary>
        /// <param name="input"></param>
        /// <returns><see langword="null"/> if CDK does not contain a reader for the detected format.</returns>
        /// <seealso cref="CreateReader(TextReader)"/>
        public ISimpleChemObjectReader CreateReader(Stream input)
        {
            IChemFormat             format = null;
            ISimpleChemObjectReader reader = null;

            if (input is GZipStream)
            {
                var istreamToRead = new ReadSeekableStream(input, 65536);
                format = formatFactory.GuessFormat(istreamToRead);
                var type = GetReaderType(format);
                if (type != null)
                {
                    try
                    {
                        reader = (ISimpleChemObjectReader)type.GetConstructor(new Type[] { typeof(Stream) }).Invoke(new object[] { istreamToRead });
                    }
                    catch (CDKException e1)
                    {
                        var wrapper = new IOException("Exception while setting the Stream: " + e1.Message, e1);
                        throw wrapper;
                    }
                }
            }
            else
            {
                var bistream      = input;
                var istreamToRead = bistream; // if gzip test fails, then take default
                                              //                bistream.Mark(5);
                int countRead = 0;
                var abMagic   = new byte[4];
                countRead = bistream.Read(abMagic, 0, 4);
                bistream.Seek(0, SeekOrigin.Begin);
                if (countRead == 4)
                {
                    if (abMagic[0] == (byte)0x1F && abMagic[1] == (byte)0x8B)
                    {
                        istreamToRead = new GZipStream(bistream, CompressionMode.Decompress);
                        return(CreateReader(istreamToRead));
                    }
                }
                format = formatFactory.GuessFormat(istreamToRead);
                var type = GetReaderType(format);
                if (type != null)
                {
                    try
                    {
                        reader = (ISimpleChemObjectReader)type.GetConstructor(new Type[] { typeof(Stream) }).Invoke(new object[] { istreamToRead });
                    }
                    catch (CDKException e1)
                    {
                        var wrapper = new IOException("Exception while setting the Stream: " + e1.Message, e1);
                        throw wrapper;
                    }
                }
            }
            return(reader);
        }
        public void TestRegisterFormat()
        {
            factory.RegisterFormat(new DummyFormat());
            StringReader reader = new StringReader("DummyFormat:");
            IChemFormat  format = factory.GuessFormat(reader);

            Assert.IsNotNull(format);
            Assert.IsTrue(format is DummyFormat);
        }
Exemple #8
0
        /// <summary>
        /// Creates a new IChemObjectWriter based on the given IChemFormat.
        /// </summary>
        public IChemObjectWriter CreateWriter(IChemFormat format, TextWriter writer)
        {
            var type = GetWriterType(format);

            if (type == null)
            {
                return(null);
            }
            return((IChemObjectWriter)type.GetConstructor(new Type[] { typeof(TextWriter) }).Invoke(new object[] { writer }));
        }
Exemple #9
0
        public virtual IChemObjectReader createReader(string filename, StreamReader input)
        {
            IChemFormat       chemFormat = guessFormatByExtension(filename);
            IChemObjectReader coReader   = createReader(chemFormat);

            try
            {
                coReader.setReader(input);
            }
            catch { }
            return(coReader);
        }
Exemple #10
0
        /// <summary>
        /// Creates a new IChemObjectReader based on the given <see cref="IChemFormat"/>.
        /// </summary>
        /// <seealso cref="CreateReader(Stream)"/>
        public Type GetReaderType(IChemFormat format)
        {
            if (format != null)
            {
                if (formatToTypeMap.TryGetValue(format, out Type clazz))
                {
                    return(clazz);
                }

                string readerClassName = format.ReaderClassName;
                if (readerClassName != null)
                {
                    try
                    {
                        // make a new instance of this class
                        clazz = this.GetType().Assembly.GetType(readerClassName);
                        foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
                        {
                            clazz = asm.GetType(readerClassName);
                            if (clazz != null)
                            {
                                break;
                            }
                        }
                        if (clazz == null)
                        {
                            clazz = this.GetType().Assembly.GetType(readerClassName, true);
                        }

                        formatToTypeMap[format] = clazz;
                        return(clazz);
                    }
                    catch (Exception exception)
                    {
                        Trace.TraceError($"Could not create this ChemObjectReader: {readerClassName}");
                        Debug.WriteLine(exception);
                    }
                }
                else
                {
                    Trace.TraceWarning("ChemFormat is recognized, but no reader is available.");
                }
            }
            else
            {
                Trace.TraceWarning("ChemFormat is not recognized.");
            }
            return(null);
        }
Exemple #11
0
        private static void ExpectFormat(string filename, IResourceFormat expectedFormat)
        {
            var ins = ResourceLoader.GetAsStream(filename);

            Assert.IsNotNull(ins, $"Cannot find file: {filename}");
            if (expectedFormat is IChemFormatMatcher)
            {
                factory.RegisterFormat((IChemFormatMatcher)expectedFormat);
            }
            ins = new BufferedStream(ins);
            IChemFormat format = factory.GuessFormat(ins);

            Assert.IsNotNull(format);
            Assert.AreEqual(expectedFormat.FormatName, format.FormatName);
        }
Exemple #12
0
        public ISimpleChemObjectReader CreateReader(IChemFormat format, TextReader input)
        {
            var type = GetReaderType(format);

            try
            {
                var coReader = (ISimpleChemObjectReader)type.GetConstructor(new Type[] { typeof(TextReader) }).Invoke(new object[] { input });
                return(coReader);
            }
            catch (Exception exception)
            {
                Trace.TraceError($"Could not set the Reader source: {exception.Message}");
                Debug.WriteLine(exception);
            }
            return(null);
        }
Exemple #13
0
 public Type GetWriterType(IChemFormat format)
 {
     if (format != null)
     {
         string writerClassName = format.WriterClassName;
         if (writerClassName != null)
         {
             try
             {
                 if (!registeredReaders.TryGetValue(writerClassName, out Type clazz))
                 {
                     clazz = this.GetType().Assembly.GetType(writerClassName);
                     if (clazz == null)
                     {
                         foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
                         {
                             clazz = asm.GetType(writerClassName);
                             if (clazz != null)
                             {
                                 break;
                             }
                         }
                     }
                     if (clazz == null)
                     {
                         clazz = this.GetType().Assembly.GetType(writerClassName, true);
                     }
                 }
                 return(clazz);
             }
             catch (Exception exception)
             {
                 Trace.TraceError($"Could not create this ChemObjectWriter: {writerClassName}");
                 Debug.WriteLine(exception);
             }
         }
         else
         {
             Trace.TraceWarning("ChemFormat is recognized, but no writer is available.");
         }
     }
     else
     {
         Trace.TraceWarning("ChemFormat is not recognized.");
     }
     return(null);
 }
Exemple #14
0
        public void TestGuessFormat_Gz()
        {
            var         filename = "NCDK.Data.XYZ.bf3.xyz.gz";
            Stream      input    = new ReadSeekableStream(new GZipStream(ResourceLoader.GetAsStream(filename), CompressionMode.Decompress), 60000);
            IChemFormat format   = factory.GuessFormat(input);

            Assert.IsNotNull(format);
            // make sure the Stream is properly reset
            var    reader = new StreamReader(input);
            string line   = reader.ReadLine();

            Assert.IsNotNull(line);
            Assert.AreEqual("4", line);
            line = reader.ReadLine();
            Assert.IsNotNull(line);
            Assert.AreEqual("Bortrifluorid", line);
        }
Exemple #15
0
        public void TestGuessFormat()
        {
            var filename = "NCDK.Data.XYZ.bf3.xyz";
            var input    = ResourceLoader.GetAsStream(filename);

            input = new BufferedStream(input);
            IChemFormat format = factory.GuessFormat(input);

            Assert.IsNotNull(format);
            // make sure the Stream is properly reset
            var    reader = new StreamReader(input);
            string line   = reader.ReadLine();

            Assert.IsNotNull(line);
            Assert.AreEqual("4", line);
            line = reader.ReadLine();
            Assert.IsNotNull(line);
            Assert.AreEqual("Bortrifluorid", line);
        }
Exemple #16
0
        public void TestGuessFormat_Reader()
        {
            var         filename = "NCDK.Data.XYZ.bf3.xyz";
            var         input    = ResourceLoader.GetAsStream(filename);
            var         reader   = new StreamReader(input);
            IChemFormat format   = factory.GuessFormat(reader);

            Assert.IsNotNull(format);
            // make sure the Reader is properly reset
            input.Seek(0, SeekOrigin.Begin);
            ((StreamReader)reader).DiscardBufferedData();
            string line = reader.ReadLine();

            Assert.IsNotNull(line);
            Assert.AreEqual("4", line);
            line = reader.ReadLine();
            Assert.IsNotNull(line);
            Assert.AreEqual("Bortrifluorid", line);
        }
Exemple #17
0
        /// <summary> Finds IChemFormats that provide a container for serialization for the
        /// given features. The syntax of the integer is explained in the DataFeatures class.
        ///
        /// </summary>
        /// <param name="features">the data features for which a IChemFormat is searched
        /// </param>
        /// <returns>          an array of IChemFormat's that can contain the given features
        ///
        /// </returns>
        /// <seealso cref="org.openscience.cdk.tools.DataFeatures">
        /// </seealso>
        public virtual IChemFormat[] findChemFormats(int features)
        {
            if (formats == null)
            {
                loadFormats();
            }

            System.Collections.IEnumerator iter    = formats.GetEnumerator();
            System.Collections.IList       matches = new System.Collections.ArrayList();
            //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'"
            while (iter.MoveNext())
            {
                //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'"
                IChemFormat format = (IChemFormat)iter.Current;
                if ((format.SupportedDataFeatures & features) == features)
                {
                    matches.Add(format);
                }
            }

            return((IChemFormat[])SupportClass.ICollectionSupport.ToArray(matches, new IChemFormat[0]));
        }
Exemple #18
0
        /// <summary> Detects the format of the Reader input, and if known, it will return
        /// a CDK Reader to read the format. This method is not able to detect the
        /// format of gziped files. Use createReader(InputStream) instead for such
        /// files.
        ///
        /// </summary>
        /// <seealso cref="createReader(InputStream)">
        /// </seealso>
        //UPGRADE_ISSUE: Class hierarchy differences between 'java.io.Reader' and 'System.IO.StreamReader' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1186'"
        public virtual IChemObjectReader createReader(System.IO.StreamReader input)
        {
            if (!(input is System.IO.StreamReader))
            {
                //UPGRADE_TODO: The differences in the expected value  of parameters for constructor 'java.io.BufferedReader.BufferedReader'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                input = new System.IO.StreamReader(input.BaseStream, input.CurrentEncoding);
            }
            IChemFormat       chemFormat = guessFormat((System.IO.StreamReader)input);
            IChemObjectReader coReader   = createReader(chemFormat);

            try
            {
                coReader.setReader(input);
            }
            catch (System.Exception exception)
            {
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                //logger.error("Could not set the Reader source: ", exception.Message);
                //logger.debug(exception);
            }
            return(coReader);
        }
Exemple #19
0
 /// <summary> Creates a new IChemObjectWriter based on the given IChemFormat.</summary>
 public virtual IChemObjectWriter createWriter(IChemFormat format)
 {
     if (format != null)
     {
         System.String writerClassName = format.WriterClassName;
         if (writerClassName != null)
         {
             try
             {
                 // make a new instance of this class
                 //UPGRADE_ISSUE: Method 'java.lang.ClassLoader.loadClass' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangClassLoader'"
                 //UPGRADE_ISSUE: Method 'java.lang.Class.getClassLoader' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangClassgetClassLoader'"
                 ObjectHandle handle = System.Activator.CreateInstance("NuGenCDKSharp", writerClassName);
                 return((IChemObjectWriter)handle.Unwrap());//System.Activator.CreateInstance(this.GetType().getClassLoader().loadClass(writerClassName));
             }
             //UPGRADE_NOTE: Exception 'java.lang.ClassNotFoundException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
             catch (System.Exception exception)
             {
                 //logger.error("Could not find this ChemObjectWriter: ", writerClassName);
                 //logger.debug(exception);
             }
             //catch (System.Exception exception)
             //{
             //    //logger.error("Could not create this ChemObjectWriter: ", writerClassName);
             //    //logger.debug(exception);
             //}
         }
         else
         {
             //logger.warn("ChemFormat is recognized, but no writer is available.");
         }
     }
     else
     {
         //logger.warn("ChemFormat is not recognized.");
     }
     return(null);
 }
        public override IEnumerator <IAtomContainer> GetEnumerator()
        {
            // buffer to store pre-read Mol records in
            var buffer = new StringBuilder(10000);

            // now try to parse the next Molecule
            currentFormat = (IChemFormat)MDLFormat.Instance;
            int lineNum = 0;

            buffer.Length = 0;

            while ((currentLine = input.ReadLine()) != null)
            {
                // still in a molecule
                buffer.Append(currentLine).Append('\n');
                lineNum++;

                // do MDL molfile version checking
                if (lineNum == 4)
                {
                    var versionMatcher = MDL_Version.Match(currentLine);
                    if (versionMatcher.Success)
                    {
                        currentFormat = string.Equals("2000", versionMatcher.Groups[1].Value, StringComparison.Ordinal)
                            ? (IChemFormat)MDLV2000Format.Instance
                            : (IChemFormat)MDLV3000Format.Instance;
                    }
                }

                if (currentLine.StartsWith(M_END, StringComparison.Ordinal))
                {
                    Debug.WriteLine($"MDL file part read: {buffer}");

                    IAtomContainer molecule = null;

                    try
                    {
                        ISimpleChemObjectReader reader = GetReader(currentFormat, new StringReader(buffer.ToString()));
                        molecule = reader.Read(builder.NewAtomContainer());
                    }
                    catch (Exception exception)
                    {
                        Trace.TraceError($"Error while reading next molecule: {exception.Message}");
                        Debug.WriteLine(exception);
                    }

                    if (molecule != null)
                    {
                        ReadDataBlockInto(molecule);
                        yield return(molecule);
                    }
                    else if (Skip)
                    {
                        // null molecule and skip = true, eat up the rest of the entry until '$$$$'
                        string line;
                        while ((line = input.ReadLine()) != null)
                        {
                            if (line.StartsWith(SDF_RECORD_SEPARATOR, StringComparison.Ordinal))
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        // don't yield
                    }

                    // empty the buffer
                    buffer.Clear();
                    lineNum = 0;
                }

                // found SDF record separator ($$$$) without parsing a molecule (separator is detected
                // in ReadDataBlockInto()) the buffer is cleared and the iterator continues reading
                if (currentLine == null)
                {
                    break;
                }
                if (currentLine.StartsWith(SDF_RECORD_SEPARATOR, StringComparison.Ordinal))
                {
                    buffer.Clear();
                    lineNum = 0;
                }
            }

            yield break;
        }
 /// <summary> Creates a new IChemObjectReader based on the given IChemFormat.
 /// 
 /// </summary>
 /// <seealso cref="createReader(InputStream)">
 /// </seealso>
 public virtual IChemObjectReader createReader(IChemFormat format)
 {
     if (format != null)
     {
         System.String readerClassName = format.ReaderClassName;
         if (readerClassName != null)
         {
             try
             {
                 // make a new instance of this class
                 ObjectHandle handle = System.Activator.CreateInstance("NuGenCDKSharp", readerClassName);
                 return (IChemObjectReader)handle.Unwrap();
             }
             catch (System.Exception exception)
             {
                 //logger.error("Could not find this ChemObjectReader: ", readerClassName);
                 //logger.debug(exception);
             }
         }
         else
         {
             // TODO: HAndle no reader available
             //logger.warn("ChemFormat is recognized, but no reader is available.");
         }
     }
     else
     {
         //logger.warn("ChemFormat is not recognized.");
     }
     return null;
 }
Exemple #22
0
 public MatchResult(bool matched, IChemFormat format, int position)
 {
     this.IsMatched = matched;
     this.format = format;
     this.Position = position;
 }
Exemple #23
0
 public void SetChemFormat(IChemFormat format)
 {
     base.SetResourceFormat(format);
     this.chemFormat = format;
 }
 /// <summary> Creates a new IChemObjectWriter based on the given IChemFormat.</summary>
 public virtual IChemObjectWriter createWriter(IChemFormat format)
 {
     if (format != null)
     {
         System.String writerClassName = format.WriterClassName;
         if (writerClassName != null)
         {
             try
             {
                 // make a new instance of this class
                 //UPGRADE_ISSUE: Method 'java.lang.ClassLoader.loadClass' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangClassLoader'"
                 //UPGRADE_ISSUE: Method 'java.lang.Class.getClassLoader' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javalangClassgetClassLoader'"
                 ObjectHandle handle = System.Activator.CreateInstance("NuGenCDKSharp", writerClassName);
                 return (IChemObjectWriter)handle.Unwrap();//System.Activator.CreateInstance(this.GetType().getClassLoader().loadClass(writerClassName));
             }
             //UPGRADE_NOTE: Exception 'java.lang.ClassNotFoundException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
             catch (System.Exception exception)
             {
                 //logger.error("Could not find this ChemObjectWriter: ", writerClassName);
                 //logger.debug(exception);
             }
             //catch (System.Exception exception)
             //{
             //    //logger.error("Could not create this ChemObjectWriter: ", writerClassName);
             //    //logger.debug(exception);
             //}
         }
         else
         {
             //logger.warn("ChemFormat is recognized, but no writer is available.");
         }
     }
     else
     {
         //logger.warn("ChemFormat is not recognized.");
     }
     return null;
 }