Skip to content
Snippets Groups Projects
DatabaseEntrySource.java 12 KiB
Newer Older
  • Learn to ignore specific revisions
  • tjc's avatar
    tjc committed
    /* DatabaseEntrySource.java
     *
     * created: Mar 2005
     *
     * This file is part of Artemis
     *
     * Copyright (C) 2001  Genome Research Limited
     *
     * 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.components;
    
    
    import javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.tree.TreePath;
    
    tjc's avatar
    tjc committed
    import java.awt.Container;
    import java.awt.GridLayout;
    
    tjc's avatar
    tjc committed
    import java.net.*;
    import java.io.*;
    import java.util.*;
    
    import uk.ac.sanger.artemis.util.*;
    import uk.ac.sanger.artemis.*;
    import uk.ac.sanger.artemis.sequence.*;
    import uk.ac.sanger.artemis.io.DatabaseDocumentEntry;
    import uk.ac.sanger.artemis.io.EntryInformation;
    import uk.ac.sanger.artemis.io.SimpleEntryInformation;
    import uk.ac.sanger.artemis.io.InvalidKeyException;
    import uk.ac.sanger.artemis.io.EntryInformationException;
    
    /**
     *
     *  This is an EntrySource that reads Entry objects from a relational
     *  database.
     *
     **/
    
    
    public class DatabaseEntrySource implements EntrySource
    
    tjc's avatar
    tjc committed
    {
    
    tjc's avatar
    tjc committed
      private String location;
    
    tjc's avatar
    tjc committed
      private JPasswordField pfield;
    
      private Hashtable entries;
    
    tjc's avatar
    tjc committed
      private boolean splitGFFEntry;
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      /**
       *  Create a new DatabaseEntrySource.
       **/
      public DatabaseEntrySource() 
      {
      }
    
      /**
       *  @param bases The Bases object to pass to the Entry constructor.
       *  @param show_progress If true a InputStreamProgressDialog will be shown
       *    while loading.  (Not implemented)
       *  @exception OutOfRangeException Thrown if one of the features in
       *    the Entry is out of range of the Bases object.
       *  @return null if and only if the read is cancelled by the user or if the
       *    read fails.
       **/
      public Entry getEntry(final Bases bases, final boolean show_progress)
          throws OutOfRangeException, IOException
      {
        return null;
      }
    
      public Entry getEntry(final boolean show_progress)
          throws OutOfRangeException, IOException
      {
        return null;
      }
    
      /**
       *  Get an Entry object from this source.
       *  @param id Feature ID to read in.
       *  @exception OutOfRangeException Thrown if one of the features in
       *    the Entry is out of range of the Bases object.
       *  @exception NoSequenceException Thrown if the entry that we read has no
       *    sequence.
       *  @return null if and only if the user cancels the read or if the read
       *    fails.
       **/
    
      public Entry getEntry(String id, InputStreamProgressListener progress_listener)
    
    tjc's avatar
    tjc committed
          throws OutOfRangeException, NoSequenceException, IOException
      {
    
        return makeFromID(null,id,false,progress_listener);
    
    tjc's avatar
    tjc committed
      }
    
      /**
       *  Returns true if and only if this EntrySource always returns "full"
       *  entries.  ie. entries that contain features and sequence.
       **/
      public boolean isFullEntrySource()
      {
        return true;
      }
    
      /**
       *  Return the name of this source (for display to the user in menus).
       **/
      public String getSourceName()
      {
        return "Database";
      }
    
    
    tjc's avatar
    tjc committed
    
      /**
      *
      * Set the database location as:
      * jdbc:postgresql://localhost:13001/chadoCVS?user=es2
      *
      */
    
      protected boolean setLocation(final boolean prompt_user)
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        Container bacross = new Container();
    
    tjc's avatar
    tjc committed
        bacross.setLayout(new GridLayout(6,2,5,5));
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
        JLabel lServer = new JLabel("Server : ");
        bacross.add(lServer);
        JTextField inServer = new JTextField("localhost");
        bacross.add(inServer);
    
        JLabel lPort = new JLabel("Port : ");
        bacross.add(lPort);
    
    tjc's avatar
    tjc committed
        JTextField inPort = new JTextField("5432");
    
    tjc's avatar
    tjc committed
        bacross.add(inPort);
    
        JLabel lDB = new JLabel("Database : ");
        bacross.add(lDB);
    
    tjc's avatar
    tjc committed
        JTextField inDB = new JTextField("chado");
    
    tjc's avatar
    tjc committed
        bacross.add(inDB);
    
        JLabel lUser = new JLabel("User : ");
        bacross.add(lUser);
    
    tjc's avatar
    tjc committed
        JTextField inUser = new JTextField("afumigatus");
    
    tjc's avatar
    tjc committed
        bacross.add(inUser);
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
        JLabel lpasswd = new JLabel("Password : ");
        bacross.add(lpasswd);
        pfield = new JPasswordField(16);
        bacross.add(pfield);
    
    
    tjc's avatar
    tjc committed
        // given -Dchado=localhost:port/dbname?username
        if(System.getProperty("chado") != null)
        {
          String db_url = System.getProperty("chado").trim();
          int index;
          if((index = db_url.indexOf(":")) > -1)
          {
            inServer.setText(db_url.substring(0,index));
            int index2;
            if((index2 = db_url.indexOf("/")) > -1)
            {
              inPort.setText(db_url.substring(index+1,index2));
              int index3;
              if((index3 = db_url.indexOf("?")) > -1)
              {
                inDB.setText(db_url.substring(index2+1,index3));
                inUser.setText(db_url.substring(index3+1));
    
    tjc's avatar
    tjc committed
    /*
    
                if(!prompt_user)
                {
                  location = "jdbc:postgresql://"
                     +inServer.getText().trim()+ ":"
                     +inPort.getText().trim()+ "/"
                     +inDB.getText().trim()+ "?user="
                     +inUser.getText().trim();
                  return true;
                }
    
    tjc's avatar
    tjc committed
    */
    
    tjc's avatar
    tjc committed
        int n = JOptionPane.showConfirmDialog(null, bacross,
    
    tjc's avatar
    tjc committed
                          "Enter Database Address",
                          JOptionPane.OK_CANCEL_OPTION,
                          JOptionPane.QUESTION_MESSAGE);
    
    tjc's avatar
    tjc committed
        if(n == JOptionPane.CANCEL_OPTION)
          return false;
    
    
    tjc's avatar
    tjc committed
        location = "jdbc:postgresql://"
          +inServer.getText().trim()+ ":"
          +inPort.getText().trim()+ "/"
          +inDB.getText().trim()+ "?user="
          +inUser.getText().trim();
    
    
    tjc's avatar
    tjc committed
         
    
    tjc's avatar
    tjc committed
         return true;
    
    tjc's avatar
    tjc committed
      }
    
    
    tjc's avatar
    tjc committed
    
    
      /**
      *
      *  Given the entry name get the seq feature_id
      *
      */
      protected String getEntryID(String name)
      {
        return (String)entries.get(name);
      }
    
      /**
      *
      * Create database organism JTree.
      *
      */
      protected JTree getDatabaseTree()
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        DatabaseDocument doc = new DatabaseDocument(location, pfield);
    
    
        entries = doc.getDatabaseEntries();
    
        Vector organism = doc.getOrganism();
    
    
        DefaultMutableTreeNode top =
            new DefaultMutableTreeNode("PSU Organism List");
        createNodes(top,organism,entries);
        final JTree tree = new JTree(top);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    
        return tree;
      }
    
      /**
      *
      * Get DefaultMutableTreeNode of selected node
      * @return     node that is currently selected
      *
      */
    
      protected String getSelectedNode(JTree tree)
    
      {
        TreePath path = tree.getLeadSelectionPath();
        if(path == null)
          return null;
    
    
        DefaultMutableTreeNode seq_node  = (DefaultMutableTreeNode)path.getLastPathComponent();
        DefaultMutableTreeNode type_node = (DefaultMutableTreeNode)seq_node.getParent();
        DefaultMutableTreeNode org_node  = (DefaultMutableTreeNode)type_node.getParent();
    
        return (String)org_node.getUserObject() + " - " +
               (String)type_node.getUserObject() + " - " +
               (String)seq_node.getUserObject();
    
      }
    
      /**
      *
      * Create the nodes of the organism JTree
      * @param top		root node
      * @param org  	organism collection
      * @param organism 	sequences collection 
      *
      */
      private void createNodes(DefaultMutableTreeNode top, Vector org,
                               Hashtable organism)
      {
        Enumeration enum_org = org.elements();
        DefaultMutableTreeNode org_node;
        DefaultMutableTreeNode seq_node;
    
        DefaultMutableTreeNode typ_node;
    
    tjc's avatar
    tjc committed
        final Object v_organism[] = organism.keySet().toArray();
        final int v_organism_size = v_organism.length;
        Arrays.sort(v_organism);
    
    tjc's avatar
    tjc committed
    
    
        while(enum_org.hasMoreElements())
        { 
          String name = (String)enum_org.nextElement();
          org_node = new DefaultMutableTreeNode(name);
          top.add(org_node);
    
    
          Hashtable seq_type_node = new Hashtable();
    
    
    tjc's avatar
    tjc committed
          for(int i=0; i<v_organism_size; i++)
    
    tjc's avatar
    tjc committed
            String seq_name = (String)v_organism[i];
    
            if(seq_name.startsWith(name))
            {
    
              int ind1 = seq_name.indexOf( "- ");
              int ind2 = seq_name.lastIndexOf("- ");
    
    
    tjc's avatar
    tjc committed
              String type =  seq_name.substring(ind1+2,ind2-1);
              seq_name = seq_name.substring(ind2+2);
    
    
              if(!seq_type_node.containsKey(type))
              {   
                typ_node = new DefaultMutableTreeNode(type);
                seq_type_node.put(type,typ_node);
                org_node.add(typ_node);          
              }
              else
                typ_node= (DefaultMutableTreeNode)seq_type_node.get(type);
             
    
              seq_node = new DefaultMutableTreeNode(seq_name);
    
              typ_node.add(seq_node);
    
    tjc's avatar
    tjc committed
      }
    
    
    tjc's avatar
    tjc committed
      protected void setSplitGFF(final boolean splitGFFEntry)
      {
        this.splitGFFEntry = splitGFFEntry;
      }
    
    tjc's avatar
    tjc committed
    
      /**
       *
       *  Given an accession number and the handle of an EMBL corba server, this
       *  method will ask the user (using a TextRequester) for the id of a entry
       *  in the server and will then attempt to get it.
       *  @param bases If this is null a new Bases object will be created for the
       *    Entry once it has been read from the server.  If not null then it will
       *    be passed to the Entry constructor.
       *  @param corba_id The id of the entry in the database
       *  @param read_only true if and only if a read-only Entry should be created
       *    (some are always read only).
       *  @exception OutOfRangeException Thrown if one of the features in
       *    the Entry is out of range of the Bases object.
       **/
      protected Entry makeFromID(final Bases bases,
                                 final String id,
    
                                 final boolean read_only,
                                 InputStreamProgressListener progress_listener)
    
    tjc's avatar
    tjc committed
          throws OutOfRangeException, IOException 
      {
        try 
        {
          DatabaseDocumentEntry db_entry = null;
    
          if(read_only) 
          {
          } 
          else 
          {
    
    tjc's avatar
    tjc committed
            DatabaseDocument doc = new DatabaseDocument(location, pfield, id, 
    
    tjc's avatar
    tjc committed
                                   splitGFFEntry, progress_listener);
    
            db_entry = new DatabaseDocumentEntry(doc);
    
    tjc's avatar
    tjc committed
          }
    
          final Bases real_bases;
    
          if(bases == null)
          {
            if(db_entry.getSequence() == null)
            {
              JOptionPane.showMessageDialog(null,
                           "The selected entry contains no sequence: " + id,
                           "No Sequence",
                           JOptionPane.ERROR_MESSAGE);
    
              return null; 
            }
    
            real_bases = new Bases(db_entry.getSequence());
          } 
          else
            real_bases = bases;
    
          return new Entry(real_bases, db_entry);
        } 
        catch(InvalidKeyException e) 
        {
          JOptionPane.showMessageDialog(null,
                           "Unexpected error while accessing " + id + ": " + e,
                           "Invalid Key",
                           JOptionPane.ERROR_MESSAGE);
        }
        catch(EntryInformationException e) 
        {
          JOptionPane.showMessageDialog(null,
                           "Failed to get entry: " + e,
                           "Entry Information Exception",
                           JOptionPane.ERROR_MESSAGE);
        }
    
        return null;
      }
    
    
    tjc's avatar
    tjc committed
      protected DatabaseDocumentEntry[] 
                             makeFromGff(final DatabaseDocument doc, String id)
                   throws OutOfRangeException, IOException
      {
        DatabaseDocumentEntry[] db_entry = null;
     
        try
        {
          DatabaseDocument[] new_docs = doc.getGffDocuments(location, id);
          db_entry = new DatabaseDocumentEntry[new_docs.length];
    
    
    tjc's avatar
    tjc committed
          for(int i=0; i<new_docs.length; i++)
            db_entry[i] = new DatabaseDocumentEntry(new_docs[i]);
    
    tjc's avatar
    tjc committed
        }
        catch(EntryInformationException e)
        {
          JOptionPane.showMessageDialog(null,
                           "Failed to get entry: " + e,
                           "Entry Information Exception",
                           JOptionPane.ERROR_MESSAGE);
        }
    
        return db_entry;
      }
    
    
    tjc's avatar
    tjc committed
    }