Import or Export a Saved Query SDF Button

    This script can be used in conjunction with an edited version of the Batch Searching script, for use on the Markush data infrastructure. The batch searching script keeps all queries in a query table, with a many:many relationship to the markush structures in the VMNS table they were found in. This may be a privacy concern for researchers who wish to keep the queries and results private, or only shared via external files. In that case, these two buttons can export a query with the resulting relationships to the VMNS structures, and then reimported to the same data structure for analysis.

    This button is written to go on a query results form, which has the VMNS table as a child, connected via a n:n relationship. This button also has two handy file formatting features: it will check for the existence of a file and confirm if you want to overwrite it, and it will check the extension to ensure it is a SDF.

    
    /** Export a saved batch query button
     *
     * @author Erin Bolstad (ebolstad@chemaxon.com)
     * Dec 2011
     */
    import com.im.commons.progress.*
    import chemaxon.formats.MolExporter
    import chemaxon.struc.Molecule
    import chemaxon.formats.MolImporter
    import javax.swing.JFileChooser
    import javax.swing.*
    
    evaluate = { widget ->
        if (SwingUtilities.isEventDispatchThread()) {
            Thread.start() {
                evaluateImpl(widget)
            }
        } else {
            evaluateImpl(widget)
        }
    }
    
    evaluateImpl = { widget ->
        def STRUCTURE_FIELD = 'Cd Structure' // field name of the structure field
        def FIELDS_FROM_CHILD = [ 'DCR Number', 'ROLE1 CODES', 'ROLE1 NAMES', 'ROLE2 CODES', 'ROLE2 NAMES' ] // list of field names from the child entity to export. Do not include structure field
    
        // Prompt for save file location
        def chooser = new JFileChooser()
        if (chooser.showSaveDialog(null)==JFileChooser.APPROVE_OPTION) {
            File fileName = chooser.getSelectedFile()
            name = fileName.getCanonicalPath()
    
            // Check to see if file has the correct extension
    
            if (!name.endsWith('.sdf')){
                FILE_NAME = name + '.sdf'
            } else {
                FILE_NAME = fileName.getCanonicalPath()
            }
    
            // See if file already exists
    
            File existFile = new File(FILE_NAME)
            if (existFile.exists () ) {
                def response = JOptionPane.showConfirmDialog (null, "$existFile exists \nOverwrite existing file?", "Confirm Overwrite", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE)
                if (response == JOptionPane.CANCEL_OPTION) {
                    return
                }
            }
        } else {
            return}
    
        def rs = widget.form.resultSet
        def dataTree = rs.dataTree
        def parent = dataTree.rootVertex.entity
        def molEdge = dataTree.rootVertex.edges.find { it.destination.entity.name == 'V Examples' }
        def molEntity = molEdge.destination.entity
        def fldMol = molEntity.fields.items.find { it.name == STRUCTURE_FIELD }
    
        def fieldsFromChild = [ ]
        FIELDS_FROM_CHILD.each { name ->
            def fld = molEntity.fields.items.find { it.name == name }
            if (fld) {
                fieldsFromChild << fld
            } else {
                JOptionPane.showMessageDialog(null, "WARNING: field $name not found", "Oh no!", JOptionPane.INFORMATION_MESSAGE)
            }
        }
    
        def ors = parent.schema.dataProvider.getDefaultResultSet(dataTree, false, DFEnvironmentRO.DEV_NULL)
        def parentVS = ors.getVertexState(dataTree.rootVertex)
        def molVS = ors.getVertexState(molEdge.destination)
        def ids = parentVS.selectedRowsIds
    
        if (ids.size == 1) {
        } else {
            throw new RuntimeException('Must select single record for export')
        }
        def id = ids[0]
    
        // now read the data
        def good = 0
    
        def exporter = new MolExporter(FILE_NAME, 'sdf')
    
        def lock = ors.lockable.obtainLock('exporting')
        try {
            def envRW = new DFEnvironmentRW() {
                public DFLock getLock() {
                    return lock;
                }
    
                public DFFeedback getFeedback() {
                    return DFEnvironmentRO.DEV_NULL.feedback;
                }
            };
    
            def mol = null
            def childIDs = molVS.ids
            def values = [ : ]
            childIDs.eachWithIndex { childID, i ->
    
                def molData = molVS.getData([childID], DFEnvironmentRO.DEV_NULL)
                mol = molData[childID][fldMol.id]
                fieldsFromChild.each {
                    values.put(it, molData[childID][it.id])
                }
    
                def expMol
                if (!mol ) {
                    expMol = new Molecule()
                } else {
                    expMol = MolImporter.importMol(mol)
                }
                values.each { k,v ->
                    if (v) {
                        expMol.setProperty(k.name, v.toString())
                    }
                }
                exporter.write(expMol)
                good++
            }
    
        } finally {
            lock?.release()
            exporter.flush()
            exporter.close()
        }
    
        JOptionPane.showMessageDialog(null, "Finished exporting data to file $FILE_NAME \n $good structures exported", "Export Complete", JOptionPane.INFORMATION_MESSAGE)
    
    }