Skip to content
Snippets Groups Projects
DatabaseDocument.java 28.2 KiB
Newer Older
  • Learn to ignore specific revisions
  • tjc's avatar
    tjc committed
    /* DatabaseDocument.java
     *
    
    tjc's avatar
    tjc committed
     * created: 2005
    
    tjc's avatar
    tjc committed
     *
     * This file is part of Artemis
     * 
    
    tjc's avatar
    tjc committed
     * Copyright (C) 2005  Genome Research Limited
    
    tjc's avatar
    tjc committed
     * 
     * This program is free software; you can redistribute it and/or
     * modify it under the terms of the GNU General Public License
     * as published by the Free Software Foundation; either version 2
     * of the License, or (at your option) any later version.
     * 
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU General Public License for more details.
     * 
     * You should have received a copy of the GNU General Public License
     * along with this program; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
     *
     */
    
    package uk.ac.sanger.artemis.util;
    
    
    tjc's avatar
    tjc committed
    import com.ibatis.sqlmap.client.SqlMapClient;
    
    tjc's avatar
    tjc committed
    import uk.ac.sanger.artemis.io.GFFStreamFeature;
    
    import uk.ac.sanger.artemis.chado.*;
    
    tjc's avatar
    tjc committed
    import uk.ac.sanger.artemis.components.DatabaseEntrySource;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
    import java.sql.*;
    
    import java.text.SimpleDateFormat;
    
    tjc's avatar
    tjc committed
    import java.io.*;
    
    tjc's avatar
    tjc committed
    import java.net.ConnectException;
    
    tjc's avatar
    tjc committed
    import java.util.Hashtable;
    
    import java.util.Vector;
    
    tjc's avatar
    tjc committed
    import java.util.Enumeration;
    
    tjc's avatar
    tjc committed
    import java.util.List;
    import java.util.Iterator;
    
    tjc's avatar
    tjc committed
    import javax.swing.JOptionPane;
    
    tjc's avatar
    tjc committed
    import javax.swing.JPasswordField;
    
    tjc's avatar
    tjc committed
    
    /**
    
    tjc's avatar
    tjc committed
     * Objects of this class are Documents created from a relational database.
     * 
     */
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
    public class DatabaseDocument extends Document
    
    tjc's avatar
    tjc committed
    {
      private String name = null;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      private String feature_id = "1";
    
    tjc's avatar
    tjc committed
    
      /** database schema */
      private String schema = "public";
    
    
    tjc's avatar
    tjc committed
      private static Hashtable cvterm;
    
    tjc's avatar
    tjc committed
    
    
      private InputStreamProgressListener progress_listener;
    
    tjc's avatar
    tjc committed
    
    
      private Hashtable db;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      /** JDBC DAO */
      private JdbcDAO jdbcDAO = null;
    
      /** iBatis DAO */
      private IBatisDAO connIB = null;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      private ByteBuffer[] gff_buffer;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      private ByteBuffer gff_buff;
    
    tjc's avatar
    tjc committed
    
      /** entries to split into */
    
    tjc's avatar
    tjc committed
      private String[] types = { "exon", "gene", "CDS", "transcript" };
    
    tjc's avatar
    tjc committed
    
      /** true if splitting the GFF into entries */
    
    tjc's avatar
    tjc committed
      private boolean splitGFFEntry;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      private boolean iBatis = false;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      private JPasswordField pfield;
    
    tjc's avatar
    tjc committed
    
    
      private List schema_list;
      
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * 
       * Create a new Document from a database.
       * 
       * @param location
       *          This should be a URL string giving:
       *          jdbc:postgresql://host:port/datbase_name?user=username
       * 
       */
    
    tjc's avatar
    tjc committed
      public DatabaseDocument(String location, JPasswordField pfield)
    
    tjc's avatar
    tjc committed
      {
        super(location);
    
    tjc's avatar
    tjc committed
        this.pfield = pfield;
    
    
    tjc's avatar
    tjc committed
        if(System.getProperty("ibatis") != null)
    
    tjc's avatar
    tjc committed
        {
    
    tjc's avatar
    tjc committed
          iBatis = true;
    
    tjc's avatar
    tjc committed
          System.setProperty("chado", location);
    
    tjc's avatar
    tjc committed
        }
    
    tjc's avatar
    tjc committed
      }
    
      /**
    
    tjc's avatar
    tjc committed
       * 
       * Create a new Document from a database.
       * 
       * @param location
       *          This should be a URL string giving:
       *          jdbc:postgresql://host:port/datbase_name?user=username
       * @param feature_id
       *          ID of a feature to be extracted.
       * 
       */
    
    tjc's avatar
    tjc committed
      public DatabaseDocument(String location, JPasswordField pfield,
    
    tjc's avatar
    tjc committed
                              String feature_id, String schema)
    
    tjc's avatar
    tjc committed
      {
        super(location);
    
    tjc's avatar
    tjc committed
        this.pfield = pfield;
    
    
    tjc's avatar
    tjc committed
        this.feature_id = feature_id;
    
    tjc's avatar
    tjc committed
        this.schema = schema;
    
    
    tjc's avatar
    tjc committed
        if(System.getProperty("ibatis") != null)
    
    tjc's avatar
    tjc committed
        {
    
    tjc's avatar
    tjc committed
          iBatis = true;
    
    tjc's avatar
    tjc committed
          System.setProperty("chado", location);
    
    tjc's avatar
    tjc committed
        }
    
    tjc's avatar
    tjc committed
      }
    
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * 
       * Create a new Document from a database.
       * 
       * @param location
       *          This should be a URL string giving:
       *          jdbc:postgresql://host:port/datbase_name?user=username
       * @param feature_id
       *          ID of a feature to be extracted.
       * @param splitGFFEntry
       *          split into separate entries based on feature types.
       * @param progress_listener
       *          input stream progress listener
       * 
       */
    
    tjc's avatar
    tjc committed
      public DatabaseDocument(String location, JPasswordField pfield,
    
    tjc's avatar
    tjc committed
                              String feature_id, String schema, boolean splitGFFEntry,
    
                              InputStreamProgressListener progress_listener)
      {
        super(location);
    
    tjc's avatar
    tjc committed
        this.pfield = pfield;
    
        this.feature_id = feature_id;
    
    tjc's avatar
    tjc committed
        this.schema = schema;
    
    tjc's avatar
    tjc committed
        this.splitGFFEntry = splitGFFEntry;
    
        this.progress_listener = progress_listener;
    
    tjc's avatar
    tjc committed
        if(System.getProperty("ibatis") != null)
    
    tjc's avatar
    tjc committed
        {
    
    tjc's avatar
    tjc committed
          iBatis = true;
    
    tjc's avatar
    tjc committed
          System.setProperty("chado", location);
    
    tjc's avatar
    tjc committed
        }
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      public DatabaseDocument(String location, JPasswordField pfield,
    
    tjc's avatar
    tjc committed
                              String feature_id, String schema,
    
    tjc's avatar
    tjc committed
                              ByteBuffer gff_buff, String name)
    
    tjc's avatar
    tjc committed
      {
        super(location);
    
    tjc's avatar
    tjc committed
        this.pfield = pfield;
    
    tjc's avatar
    tjc committed
        this.feature_id = feature_id;
    
    tjc's avatar
    tjc committed
        this.schema = schema;
        this.gff_buff = gff_buff;
    
    tjc's avatar
    tjc committed
        this.name = name;
    
    tjc's avatar
    tjc committed
        if(System.getProperty("ibatis") != null)
    
    tjc's avatar
    tjc committed
        {
    
    tjc's avatar
    tjc committed
          iBatis = true;
    
    tjc's avatar
    tjc committed
          System.setProperty("chado", location);
    
    tjc's avatar
    tjc committed
        }
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * Append a String to the Document location.
    
    tjc's avatar
    tjc committed
       * @param name  the name to append.
    
    tjc's avatar
    tjc committed
       */
      public Document append(String name) throws IOException
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        return new DatabaseDocument( ((String)getLocation()) + name, pfield);
    
    tjc's avatar
    tjc committed
      }
    
      /**
    
    tjc's avatar
    tjc committed
       * Return the name of this Document (the last element of the Document
       * location).
       */
      public String getName()
    
    tjc's avatar
    tjc committed
      {
        if(name == null)
        {
    
    tjc's avatar
    tjc committed
          int ind     = ((String) getLocation()).indexOf("?");
          String name = ((String) getLocation()).substring(0, ind);
    
    tjc's avatar
    tjc committed
          ind = name.lastIndexOf("/");
    
    tjc's avatar
    tjc committed
          return name.substring(ind + 1);
    
    tjc's avatar
    tjc committed
        }
        return name;
      }
    
    
    tjc's avatar
    tjc committed
    
      /**
      *  Set the name of this document.
      */
      public void setName(String name)
      {
        this.name = name;
      }
    
    
    tjc's avatar
    tjc committed
       * Return a Document with the last element stripped off.
       */
    
      public Document getParent()
    
    tjc's avatar
    tjc committed
      {
        return null;
      }
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * Return true if and only if the Document refered to by this object exists
       * and is readable. Always returns true.
       */
      public boolean readable()
    
    tjc's avatar
    tjc committed
      {
        return true;
      }
    
      /**
    
    tjc's avatar
    tjc committed
       * Return true if and only if the Document refered to by this object exists
       * and can be written to. Always returns false.
       */
      public boolean writable()
    
    tjc's avatar
    tjc committed
      {
        return true;
      }
    
      /**
    
    tjc's avatar
    tjc committed
       * Create a new InputStream object from this Document. The contents of the
       * Document can be read from the InputStream.
       * 
       * @exception IOException
       *              Thrown if the Document can't be read from (for example if it
       *              doesn't exist).
       */
      public InputStream getInputStream() throws IOException
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        ByteArrayInputStream instream;
    
        if(gff_buff != null)
        {
    
    tjc's avatar
    tjc committed
          instream = new ByteArrayInputStream(gff_buff.getBytes());
    
    tjc's avatar
    tjc committed
          return instream;
        }
    
    
    tjc's avatar
    tjc committed
        try
        {
    
    tjc's avatar
    tjc committed
          ChadoDAO dao = getDAO();
          gff_buffer = getGff(dao, feature_id);
    
    tjc's avatar
    tjc committed
          ByteBuffer entry = new ByteBuffer();
    
    tjc's avatar
    tjc committed
          if(splitGFFEntry)
    
    tjc's avatar
    tjc committed
          {
            if(gff_buffer[0].size() > 0)
              entry.append(gff_buffer[0]);
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
            getSequence(dao, entry);
    
    tjc's avatar
    tjc committed
          }
    
    tjc's avatar
    tjc committed
          else
          {
    
    tjc's avatar
    tjc committed
            for(int i = 0; i < gff_buffer.length; i++)
    
    tjc's avatar
    tjc committed
            {
              if(gff_buffer[i].size() > 0)
                entry.append(gff_buffer[i]);
            }
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
            getSequence(dao, entry);
    
    tjc's avatar
    tjc committed
          }
    
          instream = new ByteArrayInputStream(entry.getBytes());
    
    tjc's avatar
    tjc committed
          return instream;
        }
        catch(java.sql.SQLException sqlExp)
        {
    
    tjc's avatar
    tjc committed
          JOptionPane.showMessageDialog(null, "Problems Reading...\n" +
              sqlExp.getMessage(),
    
              "Problems Reading From the Database ",
    
    tjc's avatar
    tjc committed
              JOptionPane.ERROR_MESSAGE);
          
    
    tjc's avatar
    tjc committed
          sqlExp.printStackTrace();
        }
    
        return null;
      }
    
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * 
       * Called (by DatabaseEntrySource) to retrieve all the documents for each
       * entry created.
       * 
       */
      public DatabaseDocument[] getGffDocuments(String location, String id,
                                                String schema)
    
    tjc's avatar
    tjc committed
        int nentries = 0;
    
    tjc's avatar
    tjc committed
        for(int i = 1; i < gff_buffer.length; i++)
    
    tjc's avatar
    tjc committed
        {
          if(gff_buffer[i].size() > 0)
            nentries++;
        }
    
        DatabaseDocument[] new_docs = new DatabaseDocument[nentries];
        nentries = 0;
    
    tjc's avatar
    tjc committed
        for(int i = 1; i < gff_buffer.length; i++)
    
    tjc's avatar
    tjc committed
          if(gff_buffer[i].size() == 0)
            continue;
    
    
    tjc's avatar
    tjc committed
          String name;
          if(i >= types.length)
            name = "other";
          else
            name = types[i];
    
    
    tjc's avatar
    tjc committed
          new_docs[nentries] = new DatabaseDocument(location, pfield, id, schema,
                                                    gff_buffer[i], name);
    
    tjc's avatar
    tjc committed
          nentries++;
    
    tjc's avatar
    tjc committed
        }
    
        return new_docs;
      }
    
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * Create an array of GFF lines.
       * @param dao                 the data access object 
       * @param parentFeatureID     the parent identifier for the features to 
       *                            extract
       * @return   the <code>ByteBuffer</code> array of GFF lines
       * @throws java.sql.SQLException
    
    tjc's avatar
    tjc committed
       */
    
    tjc's avatar
    tjc committed
      private ByteBuffer[] getGff(ChadoDAO dao, String parentFeatureID)
                           throws java.sql.SQLException
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        final int srcfeature_id = Integer.parseInt(parentFeatureID);
    
    tjc's avatar
    tjc committed
        
        // build srcfeature object
        ChadoFeatureLoc featureloc = new ChadoFeatureLoc();
        featureloc.setSrcfeature_id(srcfeature_id);
        ChadoFeature feature = new ChadoFeature();
        feature.setFeatureloc(featureloc);
        
        List featList = dao.getFeature(feature, schema);
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
        ByteBuffer[] buffers = new ByteBuffer[types.length + 1];
        for(int i = 0; i < buffers.length; i++)
    
    tjc's avatar
    tjc committed
          buffers[i] = new ByteBuffer();
    
    
    tjc's avatar
    tjc committed
        String parentFeature = dao.getFeatureName(srcfeature_id, schema);
    
    tjc's avatar
    tjc committed
        ByteBuffer this_buff;
    
        int feature_size = featList.size();
    
    tjc's avatar
    tjc committed
        Hashtable id_store = new Hashtable(feature_size);
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
        // build feature name store
    
        for(int i = 0; i < feature_size; i++)
        {
    
    tjc's avatar
    tjc committed
          ChadoFeature feat = (ChadoFeature)featList.get(i);
    
          String name       = feat.getUniquename();
          String feature_id = Integer.toString(feat.getId());
    
    tjc's avatar
    tjc committed
    
          id_store.put(feature_id, name);
    
    tjc's avatar
    tjc committed
        
    
    tjc's avatar
    tjc committed
        // get all dbrefs
    
    tjc's avatar
    tjc committed
        Hashtable dbxrefs = dao.getDbxref(schema, null);
    
    tjc's avatar
    tjc committed
        
        // get all synonyms
        Hashtable synonym = dao.getAlias(schema, null);
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
        for(int i = 0; i < feature_size; i++)
    
    tjc's avatar
    tjc committed
          ChadoFeature feat = (ChadoFeature)featList.get(i);
    
    tjc's avatar
    tjc committed
          int fmin          = feat.getFeatureloc().getFmin() + 1;
          int fmax          = feat.getFeatureloc().getFmax();
    
    tjc's avatar
    tjc committed
          long type_id      = feat.getCvterm().getCvtermId();
    
    tjc's avatar
    tjc committed
          int strand        = feat.getFeatureloc().getStrand();
          int phase         = feat.getFeatureloc().getPhase();
          String name       = feat.getUniquename();
          String typeName   = getCvtermName(type_id);
    
    
          String timelastmodified = Long.toString(feat.getTimelastmodified().getTime());
    
    tjc's avatar
    tjc committed
          String feature_id       = Integer.toString(feat.getId());
    
    tjc's avatar
    tjc committed
          String parent_id = null;
    
    tjc's avatar
    tjc committed
          String parent_relationship = null;
    
    tjc's avatar
    tjc committed
          if(feat.getFeature_relationship() != null)
    
    tjc's avatar
    tjc committed
          {
            ChadoFeatureRelationship feat_relationship = feat.getFeature_relationship();
            parent_id = Integer.toString(feat_relationship.getObject_id());
            long parent_type_id = feat_relationship.getCvterm().getCvtermId();
            parent_relationship = getCvtermName(parent_type_id);
          }
    
    tjc's avatar
    tjc committed
                
    
    tjc's avatar
    tjc committed
          if(parent_id != null && id_store.containsKey(parent_id))
            parent_id = (String)id_store.get(parent_id);
    
    tjc's avatar
    tjc committed
          
    
    tjc's avatar
    tjc committed
          // make gff format
    
    tjc's avatar
    tjc committed
    
          // select buffer
          this_buff = buffers[types.length];
    
    tjc's avatar
    tjc committed
          for(int j = 0; j < types.length; j++)
    
    tjc's avatar
    tjc committed
          {
            if(types[j].equals(typeName))
              this_buff = buffers[j];
          }
    
          
          Vector dbxref = null;
          // append dbxrefs
          if(dbxrefs != null &&
             dbxrefs.containsKey(new Integer(feature_id)))
          {
            dbxref = (Vector)dbxrefs.get(new Integer(feature_id));
            for(int j=0; j<dbxref.size(); j++)
            {
              if(((String)dbxref.get(j)).startsWith("GFF_source:"))
              {
                gff_source = ((String)dbxref.get(j)).substring(11);
                dbxref.removeElementAt(j);
              }
            }
          }
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
          this_buff.append(parentFeature + "\t"); // seqid
    
          
          if(gff_source != null)
            this_buff.append(gff_source+"\t");    // source
          else
            this_buff.append("chado\t");            
    
    tjc's avatar
    tjc committed
          this_buff.append(typeName + "\t");      // type
          this_buff.append(fmin + "\t");          // start
          this_buff.append(fmax + "\t");          // end
          this_buff.append(".\t");                // score
    
    tjc's avatar
    tjc committed
          if(strand == -1)                        // strand
    
    tjc's avatar
    tjc committed
            this_buff.append("-\t");
          else if(strand == 1)
            this_buff.append("+\t");
          else
            this_buff.append(".\t");
    
    
    tjc's avatar
    tjc committed
          if(phase > 3)
            this_buff.append(".\t");               // phase
          else
            this_buff.append(phase+"\t"); 
    
    
    tjc's avatar
    tjc committed
          this_buff.append("ID=" + name + ";");
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
         
          if(parent_id != null && !parent_id.equals("0"))
          {
            if(parent_relationship.equals("derives_from"))
              this_buff.append("Derives_from=" + parent_id + ";");
            else
              this_buff.append("Parent=" + parent_id + ";");
          }
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
          this_buff.append("timelastmodified=" + timelastmodified + ";");
    
    tjc's avatar
    tjc committed
    
    
    
    tjc's avatar
    tjc committed
          // attributes
    
    tjc's avatar
    tjc committed
          Hashtable qualifiers = feat.getQualifiers();
          if(qualifiers != null && qualifiers.size() > 0)
    
    tjc's avatar
    tjc committed
          {
    
    tjc's avatar
    tjc committed
            Enumeration e_qualifiers = qualifiers.keys();
            while(e_qualifiers.hasMoreElements())
            {
              Long qualifier_type_id = (Long)e_qualifiers.nextElement();
              String qualifier_name = getCvtermName(qualifier_type_id.longValue());
              if(qualifier_name == null)
                continue;
    
    tjc's avatar
    tjc committed
              
    
    tjc's avatar
    tjc committed
              Vector qualifier_value = (Vector)qualifiers.get(qualifier_type_id);
            
              for(int j=0; j<qualifier_value.size(); j++)
              {
    
    tjc's avatar
    tjc committed
                ChadoFeatureProp featprop = (ChadoFeatureProp)qualifier_value.get(j);
    
    tjc's avatar
    tjc committed
                this_buff.append(qualifier_name+ "=" +
    
    tjc's avatar
    tjc committed
                                 GFFStreamFeature.encode(featprop.getValue())+";");
    
    tjc's avatar
    tjc committed
    
          // append dbxrefs
    
          if(dbxref != null && dbxref.size() > 0)
    
    tjc's avatar
    tjc committed
          {
            this_buff.append("Dbxref=");
            for(int j=0; j<dbxref.size(); j++)
            {
              this_buff.append((String)dbxref.get(j));
              if(j<dbxref.size()-1)
                this_buff.append(",");
            }
    
    tjc's avatar
    tjc committed
            this_buff.append(";");
    
    tjc's avatar
    tjc committed
          }
    
    tjc's avatar
    tjc committed
          
    
    tjc's avatar
    tjc committed
          // append synonyms
    
    tjc's avatar
    tjc committed
          if(synonym != null &&
             synonym.containsKey(new Integer(feature_id)))
    
    tjc's avatar
    tjc committed
          {   
    
    tjc's avatar
    tjc committed
            ChadoFeatureSynonym alias;
    
    tjc's avatar
    tjc committed
            Vector v_synonyms = (Vector)synonym.get(new Integer(feature_id));
            for(int j=0; j<v_synonyms.size(); j++)
            {
    
    tjc's avatar
    tjc committed
              alias = (ChadoFeatureSynonym)v_synonyms.get(j);
              this_buff.append(alias.getSynonym().getCvterm().getName()+"=");
              this_buff.append(alias.getSynonym().getName());
    
    tjc's avatar
    tjc committed
              if(j<v_synonyms.size()-1)
    
    tjc's avatar
    tjc committed
                this_buff.append(";");
    
    tjc's avatar
    tjc committed
            }
          }
    
    tjc's avatar
    tjc committed
          
    
    tjc's avatar
    tjc committed
          this_buff.append("\n");
    
    
    tjc's avatar
    tjc committed
          progress_listener.progressMade("Read from database: " + name);
    
    tjc's avatar
    tjc committed
        }
    
        return buffers;
    
    tjc's avatar
    tjc committed
      }
    
    
    tjc's avatar
    tjc committed
      /**
       * Look up the cvterm_id for a controlled vocabulary name.
       * @param name  
       * @return
       */
    
    tjc's avatar
    tjc committed
      public static Long getCvtermID(String name)
    
    tjc's avatar
    tjc committed
      {
        Enumeration enum_cvterm = cvterm.keys();
        while(enum_cvterm.hasMoreElements())
        {
          Long key = (Long)enum_cvterm.nextElement();
          if(name.equals(cvterm.get(key)))
    
    tjc's avatar
    tjc committed
            return key;
    
    tjc's avatar
    tjc committed
        }
    
    tjc's avatar
    tjc committed
        return null;
    
    tjc's avatar
    tjc committed
      }
    
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * Look up a cvterm name from the collection of cvterms.
       * @param id  a cvterm_id  
       * @return    the cvterm name
    
    tjc's avatar
    tjc committed
       */
      private String getCvtermName(long id)
    
    tjc's avatar
    tjc committed
      {
        if(cvterm == null)
    
    tjc's avatar
    tjc committed
        {
    
    tjc's avatar
    tjc committed
          try
          {
            getCvterm(getDAO());
          }
          catch(ConnectException ce)
          {
            ce.printStackTrace();
          }
          catch(SQLException sqle)
          {
    
    tjc's avatar
    tjc committed
            JOptionPane.showMessageDialog(null,
                "Problems Looking Up cvterm Name (cvterm_id="+
                Long.toString(id)+") ...\n" +
                sqle.getMessage(),
                "Cvterm Name Look Up",
                JOptionPane.ERROR_MESSAGE);
    
    tjc's avatar
    tjc committed
            sqle.printStackTrace();
          }
    
    tjc's avatar
    tjc committed
        }
    
    
    tjc's avatar
    tjc committed
        return (String)cvterm.get(new Long(id));
      }
    
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * Look up cvterms names and id and return in a hashtable.
    
    tjc's avatar
    tjc committed
       * @param dao the data access object
       * @return    the cvterm <code>Hashtable</code>
    
    tjc's avatar
    tjc committed
       */
    
    tjc's avatar
    tjc committed
      private Hashtable getCvterm(ChadoDAO dao)
    
    tjc's avatar
    tjc committed
      {
        cvterm = new Hashtable();
    
        try
        {
    
    tjc's avatar
    tjc committed
          List cvtem_list = dao.getCvterm();
    
    tjc's avatar
    tjc committed
          Iterator it = cvtem_list.iterator();
    
          while(it.hasNext())
          {
    
    tjc's avatar
    tjc committed
            ChadoCvterm cv = (ChadoCvterm)it.next();
    
    tjc's avatar
    tjc committed
            cvterm.put(new Long(cv.getCvtermId()), cv.getName());
    
    tjc's avatar
    tjc committed
          }
        }
    
    tjc's avatar
    tjc committed
        catch(SQLException sqle)
    
    tjc's avatar
    tjc committed
        {
          System.err.println(this.getClass() + ": SQLException retrieving CvTerms");
          System.err.println(sqle);
        }
    
        return cvterm;
      }
    
    
    tjc's avatar
    tjc committed
      /**
       * Get the sequence for a feature.
       * @param dao   the data access object
       * @param buff  the buffer to add the sequence to
       * @return      the resulting buffer
       * @throws java.sql.SQLException
       */
    
    tjc's avatar
    tjc committed
      private ByteBuffer getSequence(ChadoDAO dao, ByteBuffer buff)
                         throws java.sql.SQLException
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        ChadoFeature feature = dao.getSequence(Integer.parseInt(feature_id),
    
    tjc's avatar
    tjc committed
                                             schema);
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
        buff.append("##FASTA\n>");
    
    tjc's avatar
    tjc committed
        buff.append(feature.getUniquename());
    
    tjc's avatar
    tjc committed
        buff.append("\n");
    
    tjc's avatar
    tjc committed
        buff.append(feature.getResidues());
    
    tjc's avatar
    tjc committed
        return buff;
      }
    
    
      /**
       * Get the <code>List</code> of available schemas.
       * @return  the <code>List</code> of available schemas
       */
    
      public List getSchema()
      {
        return schema_list;
      }
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      /**
    
       * Create a hashtable of the available entries with residues.
    
    tjc's avatar
    tjc committed
       * @return a <code>Hashtable</code> of the <code>String</code>
    
       *          representation (schema-type-feature_name) and the
       *          corresponding feature_id
    
    tjc's avatar
    tjc committed
       * @throws ConnectException
       * @throws java.sql.SQLException
       */
    
    tjc's avatar
    tjc committed
      public Hashtable getDatabaseEntries()
    
    tjc's avatar
    tjc committed
                       throws ConnectException, java.sql.SQLException
    
    tjc's avatar
    tjc committed
      {
        db = new Hashtable();
    
    tjc's avatar
    tjc committed
     
    
    tjc's avatar
    tjc committed
        ChadoDAO dao = null;
        
        try
        {
          dao = getDAO();
        }
        catch(ConnectException exp)
        {
          JOptionPane.showMessageDialog(null, "Connection Problems...\n"+
                exp.getMessage(), 
                "Connection Error",
                JOptionPane.ERROR_MESSAGE);
          throw exp;
        }
        catch(java.sql.SQLException sqlExp)
        {
          JOptionPane.showMessageDialog(null, "SQL Problems...\n"+
                                        sqlExp.getMessage(), 
                                        "SQL Error",
                                        JOptionPane.ERROR_MESSAGE);
          throw sqlExp;
        }
          
    
    tjc's avatar
    tjc committed
        try
        {
    
          schema_list = dao.getSchema();
    
    tjc's avatar
    tjc committed
          Iterator it      = schema_list.iterator();
    
    tjc's avatar
    tjc committed
    
          while(it.hasNext())
          {
    
    tjc's avatar
    tjc committed
            String schema = (String)it.next();
      
    
    tjc's avatar
    tjc committed
            List list = dao.getResidueType(schema);
    
    tjc's avatar
    tjc committed
             
    
    tjc's avatar
    tjc committed
            if(list.size() == 0)  // no residues for this organism
              continue;
    
    
    tjc's avatar
    tjc committed
            List list_residue_features = dao.getResidueFeatures(list, schema);
    
    tjc's avatar
    tjc committed
            Iterator it_residue_features = list_residue_features.iterator();
            while(it_residue_features.hasNext())
            {
    
    tjc's avatar
    tjc committed
              ChadoFeature feature = (ChadoFeature)it_residue_features.next();
    
    tjc's avatar
    tjc committed
              String typeName = getCvtermName(feature.getCvterm().getCvtermId()); 
    
    tjc's avatar
    tjc committed
              
    
    tjc's avatar
    tjc committed
              db.put(schema + " - " + typeName + " - " + feature.getUniquename(),
    
    tjc's avatar
    tjc committed
                     Integer.toString(feature.getId()));
            }
    
    tjc's avatar
    tjc committed
          }
    
    tjc's avatar
    tjc committed
          
    
    tjc's avatar
    tjc committed
        }
        catch(java.sql.SQLException sqlExp)
        {
    
          JOptionPane.showMessageDialog(null, "SQL Problems...\n"+
                                        sqlExp.getMessage(), 
                                        "SQL Error",
    
    tjc's avatar
    tjc committed
                                        JOptionPane.ERROR_MESSAGE);
    
    tjc's avatar
    tjc committed
          sqlExp.printStackTrace();
        }
        return db;
      }
    
    tjc's avatar
    tjc committed
      
    
    tjc's avatar
    tjc committed
      /**
       * Get the data access object (DAO).
       * @return data access object
       */
      private ChadoDAO getDAO()
         throws java.net.ConnectException, SQLException
      {
        if(!iBatis)
        {
          if(jdbcDAO == null)
           jdbcDAO = new JdbcDAO((String)getLocation(), pfield); 
          return jdbcDAO;
        }
        else
        {
          if(connIB == null)
            connIB = new IBatisDAO(pfield);
          return connIB;
        }
      }
    
    
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * Create a new OutputStream object from this Document. The contents of the
       * Document can be written from the stream.
       * 
       * @exception IOException
       *              Thrown if the Document can't be written.
       */
    
    tjc's avatar
    tjc committed
      public OutputStream getOutputStream() throws IOException
      {
    
    tjc's avatar
    tjc committed
        final File write_file = new File(System.getProperty("user.dir")+
                                         System.getProperty("file.separator")+
                                         getName());
    
        final FileOutputStream file_output_stream =
          new FileOutputStream(write_file);
    
        if(write_file.getName().endsWith(".gz")) 
        {
          // assume this file should be gzipped
          return new java.util.zip.GZIPOutputStream (file_output_stream);
        } 
        else 
          return file_output_stream;
    
    tjc's avatar
    tjc committed
      }
    
    
    tjc's avatar
    tjc committed
      /**
       * Commit the <code>ChadoTransaction</code> SQL back to the
       * database.
       * @param sql the collection of <code>ChadoTransaction</code> objects
       * @return
       */
      public int commit(Vector sql)
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        int i = 0;
    
    tjc's avatar
    tjc committed
        try
        {
    
    tjc's avatar
    tjc committed
          ChadoDAO dao = getDAO();
    
          boolean unchanged;
          
          //
          // check feature timestamps have not changed
    
          Vector names_checked = new Vector();
    
    tjc's avatar
    tjc committed
          for(i = 0; i < sql.size(); i++)
    
    tjc's avatar
    tjc committed
          {
    
    tjc's avatar
    tjc committed
            ChadoTransaction tsn = (ChadoTransaction) sql.get(i);
    
    tjc's avatar
    tjc committed
     
    
            if(tsn.getType() != ChadoTransaction.INSERT_FEATURE ||
               tsn.getType() != ChadoTransaction.DELETE_FEATURE)
    
    tjc's avatar
    tjc committed
            {
              final List uniquename = tsn.getUniquename();
    
    tjc's avatar
    tjc committed
              
    
    tjc's avatar
    tjc committed
              for(int j=0; j<uniquename.size(); j++)
    
              {
                if(names_checked.contains((String)uniquename.get(j)))
                  continue;
                
                names_checked.add((String)uniquename.get(j));
    
                unchanged = checkFeatureTimestamp(schema, 
                               (String)uniquename.get(j), 
                             tsn.getLastModified(), dao);
                if(!unchanged)
                  return 0;
              }
    
    tjc's avatar
    tjc committed
            }
    
          }  
           
          //
          // commit to database
          for(i = 0; i < sql.size(); i++)
          {
            ChadoTransaction tsn = (ChadoTransaction) sql.get(i);
    
            
            if(tsn.getType() == ChadoTransaction.UPDATE)
              dao.updateAttributes(schema, tsn);
    
    tjc's avatar
    tjc committed
            else if(tsn.getType() == ChadoTransaction.INSERT)
              dao.insertAttributes(schema, tsn);
            else if(tsn.getType() == ChadoTransaction.DELETE)
              dao.deleteAttributes(schema, tsn);
    
    tjc's avatar
    tjc committed
            else if(tsn.getType() == ChadoTransaction.INSERT_FEATURE)
              dao.insertFeature(schema, tsn, feature_id);
    
    tjc's avatar
    tjc committed
            else if(tsn.getType() == ChadoTransaction.DELETE_FEATURE)
              dao.deleteFeature(schema, tsn);
    
    tjc's avatar
    tjc committed
            else if(tsn.getType() == ChadoTransaction.DELETE_DBXREF)
              dao.deleteFeatureDbxref(schema, tsn);
    
    tjc's avatar
    tjc committed
            else if(tsn.getType() == ChadoTransaction.INSERT_DBXREF)
              dao.insertFeatureDbxref(schema, tsn);
    
    tjc's avatar
    tjc committed
            else if(tsn.getType() == ChadoTransaction.DELETE_ALIAS)
              dao.deleteFeatureAlias(schema, tsn);
            else if(tsn.getType() == ChadoTransaction.INSERT_ALIAS)
              dao.insertFeatureAlias(schema, tsn);
    
    tjc's avatar
    tjc committed
          }
    
          
          
          //
          // update timelastmodified timestamp
    
          Timestamp ts = null;
          Timestamp ts2;
    
          names_checked = new Vector();
    
          for(int j = 0; j < sql.size(); j++)
          {
            ChadoTransaction tsn = (ChadoTransaction) sql.get(j);
    
            if(tsn.getType() != ChadoTransaction.INSERT_FEATURE ||
               tsn.getType() != ChadoTransaction.DELETE_FEATURE)
            {
              final List uniquename = tsn.getUniquename();
              
              // update timelastmodified timestamp
              for(int k=0; k<uniquename.size(); k++)
              {
    
                if(names_checked.contains((String)uniquename.get(k)))
                  continue;
                
                names_checked.add((String)uniquename.get(k));
                
    
                dao.writeTimeLastModified(schema, (String)uniquename.get(k), ts);
                ts2 = dao.getTimeLastModified(schema, (String)uniquename.get(k));
                if(ts2 == null)
    
    tjc's avatar
    tjc committed
                  continue;
    
                GFFStreamFeature gff_feature = (GFFStreamFeature)tsn.getFeatureObject();
    
                gff_feature.setLastModified(ts);
    
    tjc's avatar
    tjc committed
        }
    
    tjc's avatar
    tjc committed
        catch (java.sql.SQLException sqlExp)
    
    tjc's avatar
    tjc committed
        {
    
    tjc's avatar
    tjc committed
          JOptionPane.showMessageDialog(null, "Problems Writing...\n" +
    
    tjc's avatar
    tjc committed
                                        sqlExp.getMessage(),
    
    tjc's avatar
    tjc committed
                                        "Problems Writing to Database ",
    
    tjc's avatar
    tjc committed
                                        JOptionPane.ERROR_MESSAGE);
    
    tjc's avatar
    tjc committed
          sqlExp.printStackTrace();
        }
    
    tjc's avatar
    tjc committed
        catch (java.net.ConnectException conn_ex)
    
    tjc's avatar
    tjc committed
        {
    
    tjc's avatar
    tjc committed
          JOptionPane.showMessageDialog(null, "Problems connecting..."+
                                        conn_ex.getMessage(),
    
    tjc's avatar
    tjc committed
                                        "Database Connection Error - Check Server",
                                        JOptionPane.ERROR_MESSAGE);
    
    tjc's avatar
    tjc committed
          conn_ex.printStackTrace();
    
    tjc's avatar
    tjc committed
        }
    
    tjc's avatar
    tjc committed
        return i;
    
    tjc's avatar
    tjc committed
      }
    
      
      /**
       * Check the <code>Timestamp</code> on a feature (for versioning).
       * @param schema      the schema
       * @param uniquename  the feature uniquename
       * @param timestamp   the last read feature timestamp
       * @throws SQLException
       */
    
      public boolean checkFeatureTimestamp(final String schema,
    
    tjc's avatar
    tjc committed
                                           final String uniquename,
                                           final Timestamp timestamp,
                                           final ChadoDAO dao)
                                           throws SQLException
    
      {
        Timestamp now = dao.getTimeLastModified(schema, uniquename);
        
    
    tjc's avatar
    tjc committed
        if(now != null && timestamp != null)
    
        {
          now.setNanos(0);
          timestamp.setNanos(0);
          
    
          if(now.compareTo(timestamp) != 0)
          {
            SimpleDateFormat date_format = 
                       new SimpleDateFormat("dd.MM.yyyy hh:mm:ss z");
    
            //System.out.println(date_format.format(now)+"   "+
            //                   date_format.format(timestamp));
    
            int select = JOptionPane.showConfirmDialog(null, uniquename +
    
                                          " has been altered at :\n"+
    
                                          date_format.format(now)+"\nOverwite?", 
                                          "Feature Changed", 
                                          JOptionPane.OK_CANCEL_OPTION);
            if(select == JOptionPane.OK_OPTION)
              return true;
            else
              return false;
    
        return true;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      public static void main(String args[])
      {
        try
        {
    
    tjc's avatar
    tjc committed
          ChadoDAO dao;
          DatabaseEntrySource src = new DatabaseEntrySource();
          src.setLocation(true);
          
          if(System.getProperty("ibatis") == null)
            dao = new JdbcDAO(src.getLocation(), src.getPfield()); 
          else
            dao = new IBatisDAO(src.getPfield());
          
    
    tjc's avatar
    tjc committed
          ChadoFeature feature = new ChadoFeature();
          feature.setUniquename(args[0]);
    
    tjc's avatar
    tjc committed
          List schemas = new Vector();
          schemas.add(args[1]);
    
    tjc's avatar
    tjc committed
          List featureList = dao.getLazyFeature(feature, schemas); 
    
    tjc's avatar
    tjc committed
          System.out.println("FINISHED getFeature()");
    
    tjc's avatar
    tjc committed
          for(int i = 0; i < featureList.size(); i++)
          {
    
    tjc's avatar
    tjc committed
            feature = (ChadoFeature)featureList.get(i);
    
    tjc's avatar
    tjc committed
            
    
    tjc's avatar
    tjc committed
            String abb  = feature.getOrganism().getAbbreviation();
    
    tjc's avatar
    tjc committed
            String type = feature.getCvterm().getName();
    
    tjc's avatar
    tjc committed
            int fmin    = feature.getFeatureloc().getFmin() + 1;
            int fmax    = feature.getFeatureloc().getFmax();
    
    tjc's avatar
    tjc committed
            String featprop = 
              ((ChadoFeatureProp)feature.getFeaturepropList().get(0)).getCvterm().getName();
            
    
    tjc's avatar
    tjc committed
            System.out.print(fmin+".."+fmax);
    
    tjc's avatar
    tjc committed
            System.out.print(" "+type);
    
    tjc's avatar
    tjc committed
            System.out.print(" "+featprop);
    
    tjc's avatar
    tjc committed
            System.out.print(" "+feature.getFeatureloc().getStrand());
    
    tjc's avatar
    tjc committed
            System.out.print(" "+feature.getUniquename());
    
    tjc's avatar
    tjc committed
            System.out.print(" "+abb);
    
    tjc's avatar
    tjc committed
            System.out.println(" "+Integer.toString(feature.getId()));
    
    tjc's avatar
    tjc committed
            
            Hashtable synonyms   = dao.getAlias(args[1], feature.getUniquename());
            Vector syns = (Vector)synonyms.get(new Integer(feature.getId()));
            for(int j=0; j<syns.size(); j++)
            {
    
    tjc's avatar
    tjc committed
              ChadoFeatureSynonym alias = (ChadoFeatureSynonym)syns.get(j);
              System.out.print(" "+alias.getSynonym().getCvterm().getName()+
                               "="+alias.getSynonym().getName());
    
    tjc's avatar
    tjc committed
            }
            
            System.out.println(" "); 
    
    tjc's avatar
    tjc committed
          }
    
    tjc's avatar
    tjc committed
        }
        catch(SQLException sqle)
        {
          sqle.printStackTrace();
        }
    
    tjc's avatar
    tjc committed
        catch(ConnectException e)
        {
          e.printStackTrace();
        }
    
    tjc's avatar
    tjc committed
      }
    
    tjc's avatar
    tjc committed
    }