Skip to content
Snippets Groups Projects
DatabaseDocument.java 93 KiB
Newer Older
  • Learn to ignore specific revisions
  • tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
      /**
       * Get the CDS FeatureLoc's associated with a give protein
       * @param peptideName
       * @return
       */
      public List getCdsFeatureLocsByPeptideName(final String peptideName)
    
    tjc's avatar
    tjc committed
      {
        Feature peptideFeature = getFeatureByUniquename(peptideName);
    
    tjc's avatar
    tjc committed
        Collection frs = peptideFeature.getFeatureRelationshipsForSubjectId();
        Iterator it = frs.iterator();
        Feature transcriptFeature = null;
        while(it.hasNext())
        {
          FeatureRelationship fr = (FeatureRelationship)it.next();
          if(fr.getCvTerm().getName().equalsIgnoreCase("derives_from"))
          {
            transcriptFeature = fr.getFeatureByObjectId();
            logger4j.debug("TRANSCRIPT :: "+transcriptFeature.getUniqueName());
            break;
          }
        }
    
    tjc's avatar
    tjc committed
        
    
    tjc's avatar
    tjc committed
        if(transcriptFeature == null)
          return null;
        return getCdsFeatureLocsByTranscriptName(transcriptFeature.getUniqueName());
    
    tjc's avatar
    tjc committed
      }
      
    
       * Get the CDS FeatureLoc's associated with a given transcript
    
    tjc's avatar
    tjc committed
       * @param transcriptName
       * @return
       */
      public List getCdsFeatureLocsByTranscriptName(final String transcriptName)
    
    tjc's avatar
    tjc committed
      {
        Feature transcriptFeature = getFeatureByUniquename(transcriptName);
        if(transcriptFeature == null)
    
    tjc's avatar
    tjc committed
          return null;
    
    tjc's avatar
    tjc committed
        
        Collection frs = transcriptFeature.getFeatureRelationshipsForObjectId();
        Iterator it = frs.iterator();
    
    tjc's avatar
    tjc committed
        List cdsFeatureLocs = new Vector();
    
    tjc's avatar
    tjc committed
        while(it.hasNext())
        {
          FeatureRelationship fr = (FeatureRelationship)it.next();
    
    tjc's avatar
    tjc committed
          org.gmod.schema.sequence.Feature child = fr.getFeatureBySubjectId();
          if(child.getCvTerm().getName().equals("exon") || 
             child.getCvTerm().getName().equals("pseudogenic_exon"))
    
    tjc's avatar
    tjc committed
          {
    
    tjc's avatar
    tjc committed
            Collection featureLocs = child.getFeatureLocsForFeatureId();
    
            Iterator it2 = featureLocs.iterator();
            while(it2.hasNext())
            {
              FeatureLoc featureLoc = (FeatureLoc) it2.next();
              cdsFeatureLocs.add(featureLoc);
            }
    
    tjc's avatar
    tjc committed
          }
        }
    
    tjc's avatar
    tjc committed
        Collections.sort(cdsFeatureLocs, new LocationComarator());
    
    tjc's avatar
    tjc committed
        return cdsFeatureLocs;
    
    tjc's avatar
    tjc committed
      }
    
      
      /**
       * Get the sequence for a feature.
    
    tjc's avatar
    tjc committed
       * @param uniqueName   the feature
    
       * @return      the resulting buffer
       */
      public PartialSequence getChadoSequence(final String uniqueName)
      {
    
    tjc's avatar
    tjc committed
        Feature feature = getDAOOnly().getResiduesByUniqueName(uniqueName);
        char[] c = getChars(feature.getResidues());
        
        PartialSequence ps = new PartialSequence(c, feature.getSeqLen(),
                                    feature.getFeatureLoc().getFmin().intValue()+1,
    
    tjc's avatar
    tjc committed
                                    feature.getFeatureLoc().getStrand(),
                                    feature.getFeatureLoc().getPhase());
    
    tjc's avatar
    tjc committed
        return ps;
      }
      
      /**
       * Convert byte array to char array
       * @param b byte array
       * @return  char array
       */
      private char[] getChars(final byte b[])
      {
    
        char[] c = new char[b.length];
    
        for(int i = 0; i < b.length; i++)
          c[i] = (char)b[i];
    
    tjc's avatar
    tjc committed
        return c;
    
      /**
       * 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
      public Feature getFeatureByUniquename(final String uniqueName) 
      {
        GmodDAO dao = getDAOOnly();
        List features = dao.getFeaturesByUniqueName(uniqueName);
        if(features == null || features.size() < 1)
          return null;
          
        return (Feature)(dao.getFeaturesByUniqueName(uniqueName).get(0));
      }
      
      /**
       * Given a gene unique name return the poplypeptide chado features that belong
       * to that gene
       * @param geneName
       * @return
       */
      public Vector getPolypeptideFeatures(final String geneName)
      {
        Feature geneFeature =  getFeatureByUniquename(geneName);
        if(geneFeature == null)
          return null;
        
        Collection frs = geneFeature.getFeatureRelationshipsForObjectId();
        Iterator it = frs.iterator();
        List transcripts = new Vector(frs.size());
        while(it.hasNext())
        {
          FeatureRelationship fr = (FeatureRelationship)it.next();
          transcripts.add(fr.getFeatureBySubjectId());
        }
        
        Vector polypep = new Vector();
        for(int i=0; i<transcripts.size(); i++)
        {
          org.gmod.schema.sequence.Feature transcript = 
            (org.gmod.schema.sequence.Feature) transcripts.get(i);
          frs = transcript.getFeatureRelationshipsForObjectId();
          it = frs.iterator();
          while(it.hasNext())
          {
            FeatureRelationship fr = (FeatureRelationship)it.next();
            if(fr.getCvTerm().getName().equalsIgnoreCase("derives_from"))
              if(fr.getFeatureBySubjectId().getCvTerm().getName().equalsIgnoreCase("polypeptide"))
                polypep.add(fr.getFeatureBySubjectId());
          }
        }
        return polypep;
      }
      
      /**
       * Given a gene unique name return the poplypeptides that belong
       * to that gene
       * @param geneName
       * @return
       */
    
    tjc's avatar
    tjc committed
      /*public Vector getPolypeptideNames(final String geneName)
    
    tjc's avatar
    tjc committed
      {
        Vector polypeptides = getPolypeptideFeatures(geneName);
        Vector polypeptideNames = new Vector(polypeptides.size());
        for(int i=0; i<polypeptides.size(); i++)
        {
          Feature feature = (Feature)polypeptides.get(i);
          polypeptideNames.add(feature.getUniqueName());
        }
        return polypeptideNames;
    
    tjc's avatar
    tjc committed
      }*/
    
    tjc's avatar
    tjc committed
      
    
    tjc's avatar
    tjc committed
      public List getClustersByFeatureIds(final List featureIds)
      {
        GmodDAO dao = getDAOOnly();
        return dao.getClustersByFeatureIds(featureIds);
      }
    
      public List getParentFeaturesByChildFeatureIds(final List subjectIds)
      {
        GmodDAO dao = getDAOOnly();
        return dao.getParentFeaturesByChildFeatureIds(subjectIds);
      }
      
    
    tjc's avatar
    tjc committed
      public List getFeatureDbXRefsByFeatureId(final List featureIds)
      {
        GmodDAO dao = getDAOOnly();
        return dao.getFeatureDbXRefsByFeatureId(featureIds);
      }
      
    
    tjc's avatar
    tjc committed
      /**
    
    tjc's avatar
    tjc committed
       * Used by SimilarityLazyQualifierValue.bulkRetrieve() to get the match features
    
    tjc's avatar
    tjc committed
       * @param featureIds the <code>List</code> of feature_id's
       * @return  the corresponding features
       */
      public List getFeaturesByListOfIds(final List featureIds)
      {
        GmodDAO dao = getDAOOnly();
        return dao.getFeaturesByListOfIds(featureIds);
      }
      
      public List getFeaturePropByFeatureIds(final List featureIds)
      {
        GmodDAO dao = getDAOOnly();
        return dao.getFeaturePropByFeatureIds(featureIds);
      }
      
    
      public List getSimilarityMatches(List featureIds)
    
    tjc's avatar
    tjc committed
        GmodDAO dao = getDAOOnly();
        if(featureIds == null)
          return dao.getSimilarityMatches(new Integer(srcFeatureId));
        else
          return dao.getSimilarityMatchesByFeatureIds(featureIds);
    
    tjc's avatar
    tjc committed
      
    
      public List getFeatureLocsByListOfIds(List featureIds)
      {
        GmodDAO dao = getDAOOnly();
        return dao.getFeatureLocsByListOfIds(featureIds);
      }
      
    
    tjc's avatar
    tjc committed
      /**
       * Create a hashtable of the available entries with residues.
       * @return a <code>Hashtable</code> of the <code>String</code>
       *          representation (schema-type-feature_name) and the
       *          corresponding feature_id
       * @throws ConnectException
       * @throws java.sql.SQLException
       */
    
    tjc's avatar
    tjc committed
      public HashMap getDatabaseEntriesMultiSchema()
    
    tjc's avatar
    tjc committed
                       throws ConnectException, java.sql.SQLException
      {
        String schema = null;
    
    tjc's avatar
    tjc committed
        HashMap db    = null;
    
    tjc's avatar
    tjc committed
        try
        { 
    
          GmodDAO dao = getDAO();
    
    tjc's avatar
    tjc committed
          schema_list = dao.getSchema(); 
    
    tjc's avatar
    tjc committed
          
    
    tjc's avatar
    tjc committed
          Iterator it = schema_list.iterator();
    
    tjc's avatar
    tjc committed
            
    
    tjc's avatar
    tjc committed
          while(it.hasNext())
          {
    
            schema = (String)it.next();
    
    tjc's avatar
    tjc committed
            
            reset((String)getLocation(),  schema);
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
            try
            {
              dao = getDAO();
    
    tjc's avatar
    tjc committed
              List list_residue_features = dao.getResidueFeatures();
    
    tjc's avatar
    tjc committed
              Iterator it_residue_features = list_residue_features.iterator();
              while(it_residue_features.hasNext())
              {
                Feature feature = (Feature)it_residue_features.next();
    
                String typeName = getCvtermName(feature.getCvTerm().getCvTermId(), getDAO(), gene_builder); 
    
    tjc's avatar
    tjc committed
              
    
    tjc's avatar
    tjc committed
                if(db == null)
                  db = new HashMap();
    
    tjc's avatar
    tjc committed
                db.put(schema + " - " + typeName + " - " + feature.getUniqueName(),
                       Integer.toString(feature.getFeatureId()));
              }
            }
    
            catch(RuntimeException e){}
            catch(java.sql.SQLException sqlExp){}
    
    tjc's avatar
    tjc committed
          }
          
        }
        catch(RuntimeException sqlExp)
        {
          JOptionPane.showMessageDialog(null, "SQL Problems...\n"+
                                        sqlExp.getMessage(), 
                                        "SQL Error",
                                        JOptionPane.ERROR_MESSAGE);
    
    tjc's avatar
    tjc committed
          
          logger4j.debug(sqlExp.getMessage());
          //sqlExp.printStackTrace();
    
    tjc's avatar
    tjc committed
        }
        catch(ConnectException exp)
        {
          JOptionPane.showMessageDialog(null, "Connection Problems...\n"+
                exp.getMessage(), 
                "Connection Error",
                JOptionPane.ERROR_MESSAGE);
    
    tjc's avatar
    tjc committed
          logger4j.debug(exp.getMessage());
    
    tjc's avatar
    tjc committed
          throw exp;
        }
        catch(java.sql.SQLException sqlExp)
    
    tjc's avatar
    tjc committed
        {
          JOptionPane.showMessageDialog(null, "SQL Problems....\n"+
                                        sqlExp.getMessage(), 
                                        "SQL Error",
                                        JOptionPane.ERROR_MESSAGE);
          logger4j.debug(sqlExp.getMessage());
          throw sqlExp;
        }
        
        return db;
      }
      
      
      /**
       * Create a hashtable of the available entries with residues.
    
    tjc's avatar
    tjc committed
       * 
    
    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
       * @throws ConnectException
       * @throws java.sql.SQLException
       */
    
    tjc's avatar
    tjc committed
      public HashMap getDatabaseEntries()
    
    tjc's avatar
    tjc committed
                       throws ConnectException, java.sql.SQLException
      {
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
        HashMap db = null;
    
    tjc's avatar
    tjc committed
        try
        { 
          GmodDAO dao = getDAO();
    
    tjc's avatar
    tjc committed
          CvTermThread cvThread = new CvTermThread(dao);
          cvThread.start();
          
    
    tjc's avatar
    tjc committed
          schema_list = dao.getOrganisms();
    
    tjc's avatar
    tjc committed
          
    
          /*Organism org = new Organism();
    
    tjc's avatar
    tjc committed
          org.setCommonName("web");
    
          schema_list.add(org);*/
    
    tjc's avatar
    tjc committed
          
    
    tjc's avatar
    tjc committed
          final List pg_schemas = dao.getSchema();
          
          // build a lookup hash of residue features in the
          // main schema
          Hashtable residueFeaturesLookup = new Hashtable();
          List list_residue_features = dao.getResidueFeatures();
          for(int i=0; i<list_residue_features.size(); i++)
          {
            Feature feature = (Feature)list_residue_features.get(i);
            Integer organismId = new Integer(feature.getOrganism().getOrganismId());
            List features;
            if(residueFeaturesLookup.containsKey(organismId))
              features= (List)residueFeaturesLookup.get(organismId);
            else
              features = new Vector();
            features.add(feature);
            residueFeaturesLookup.put(organismId, features);
          }
          
          // loop over organisms to identify those with features 
          // containing residues
    
    tjc's avatar
    tjc committed
          Iterator it = schema_list.iterator();
    
    tjc's avatar
    tjc committed
          while(it.hasNext())
          {
    
    tjc's avatar
    tjc committed
            final Organism organism = (Organism)it.next();
            String orgName = organism.getCommonName();
            
    
            if(orgName == null || orgName.equals(""))
            {
              orgName = organism.getGenus() + "." + organism.getSpecies();
              organism.setCommonName(orgName);
            }
            
    
    tjc's avatar
    tjc committed
            // search to see if this is in its own schema
            Iterator schemasIt = pg_schemas.iterator();
            while(schemasIt.hasNext())
            {
    
    tjc's avatar
    tjc committed
              schema = (String)schemasIt.next();         
    
    tjc's avatar
    tjc committed
              if( schema.equalsIgnoreCase(organism.getCommonName()) )
              {
                reset((String)getLocation(),  schema);
                dao = getDAO();
                orgName = schema;
    
    
    tjc's avatar
    tjc committed
                singleSchema = false;
    
    tjc's avatar
    tjc committed
                break;
              }
            }
    
    tjc's avatar
    tjc committed
              if(organism.getOrganismId() > 0)
    
    tjc's avatar
    tjc committed
              {
                Integer organismId = new Integer(organism.getOrganismId());
                
                if(residueFeaturesLookup.containsKey(organismId))
                  list_residue_features = (List)residueFeaturesLookup.get(organismId);
                else if(singleSchema && residueFeaturesLookup.size()>0)
                  continue;
                else
                  list_residue_features = dao.getResidueFeatures(organismId);
              }
    
    tjc's avatar
    tjc committed
              else
    
    tjc's avatar
    tjc committed
                list_residue_features = 
                  dao.getResidueFeaturesByOrganismCommonName(organism.getCommonName());
    
    tjc's avatar
    tjc committed
              
              Iterator it_residue_features = list_residue_features.iterator();
              while(it_residue_features.hasNext())
              {
    
    tjc's avatar
    tjc committed
                final Feature feature = (Feature)it_residue_features.next();
                final String typeName = feature.getCvTerm().getName();
    
    tjc's avatar
    tjc committed
                      
                if(db == null)
                  db = new HashMap();
    
    tjc's avatar
    tjc committed
                if(organismNames == null)
                  organismNames = new Vector();
                
                if(!organismNames.contains(orgName))
                  organismNames.add(orgName);         
                
    
    tjc's avatar
    tjc committed
                db.put(orgName + " - " + typeName + " - " + feature.getUniqueName(),
                       Integer.toString(feature.getFeatureId())); 
    
    tjc's avatar
    tjc committed
              }
            }
            catch(RuntimeException e)
            {
              e.printStackTrace();
            }
          }
          
    
    tjc's avatar
    tjc committed
          residueFeaturesLookup.clear();
          list_residue_features.clear();
    
    tjc's avatar
    tjc committed
          
          // now wait for cvterm to be loaded
          while(cvThread.isAlive())
            Thread.sleep(10);
    
    tjc's avatar
    tjc committed
        }
        catch(RuntimeException sqlExp)
        {
          JOptionPane.showMessageDialog(null, "SQL Problems...\n"+
    
    tjc's avatar
    tjc committed
                                        getLocation()+"\n"+
    
    tjc's avatar
    tjc committed
                                        sqlExp.getMessage(), 
                                        "SQL Error",
                                        JOptionPane.ERROR_MESSAGE);
          
          logger4j.debug(sqlExp.getMessage());
          //sqlExp.printStackTrace();
        }
        catch(ConnectException exp)
        {
          JOptionPane.showMessageDialog(null, "Connection Problems...\n"+
                exp.getMessage(), 
                "Connection Error",
                JOptionPane.ERROR_MESSAGE);
          logger4j.debug(exp.getMessage());
          throw exp;
        }
        catch(java.sql.SQLException sqlExp)
    
    tjc's avatar
    tjc committed
        {
          JOptionPane.showMessageDialog(null, "SQL Problems....\n"+
    
    tjc's avatar
    tjc committed
                                        getLocation()+"\n"+
    
    tjc's avatar
    tjc committed
                                        sqlExp.getMessage(), 
                                        "SQL Error",
                                        JOptionPane.ERROR_MESSAGE);
    
    tjc's avatar
    tjc committed
          logger4j.debug(sqlExp.getMessage());
    
    tjc's avatar
    tjc committed
          throw sqlExp;
        }
    
    tjc's avatar
    tjc committed
        catch(InterruptedException e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
    
    tjc's avatar
    tjc committed
        
        return db;
      }
      
    
    tjc's avatar
    tjc committed
      /**
       * 
       */
      public void showCvTermLookUp()
      {
        try
        {
          new ChadoCvTermView( getDAO() );
        }
        catch(ConnectException e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        catch(SQLException e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    
    tjc's avatar
    tjc committed
      
    
    tjc's avatar
    tjc committed
      /**
       * Get the data access object (DAO).
       * @return data access object
       */
    
      private GmodDAO getDAO()
    
    tjc's avatar
    tjc committed
         throws java.net.ConnectException, SQLException
    
    tjc's avatar
    tjc committed
      { 
    
    tjc's avatar
    tjc committed
        if(!iBatis)
        {
          if(jdbcDAO == null)
           jdbcDAO = new JdbcDAO((String)getLocation(), pfield); 
          return jdbcDAO;
        }
        else
    
    tjc's avatar
    tjc committed
        {   
    
    tjc's avatar
    tjc committed
          if(connIB == null)
    
    tjc's avatar
    tjc committed
          {
            System.setProperty("chado", (String)getLocation());
    
    tjc's avatar
    tjc committed
            connIB = new IBatisDAO(pfield);
    
    tjc's avatar
    tjc committed
          }
    
    tjc's avatar
    tjc committed
          return connIB;
        }
      }
    
    tjc's avatar
    tjc committed
      /**
       * Get the username for this connection
       * @return
       */
      public String getUserName()
      {
        // "localhost:10001/backup?chado"
        
        String url = (String)getLocation();
        int index  = url.indexOf("?");
        
        String userName = url.substring(index+1).trim();
        if(userName.startsWith("user="))
          userName = userName.substring(5);
        
        return userName;
      }
      
    
    tjc's avatar
    tjc committed
      private GmodDAO getDAOOnly()
      {
        GmodDAO dao = null;
        try
        {
          dao = getDAO();
        }
        catch(RuntimeException sqlExp)
        {
          JOptionPane.showMessageDialog(null, "SQL Problems...\n"+
                                        sqlExp.getMessage(), 
                                        "SQL Error",
                                        JOptionPane.ERROR_MESSAGE);
        }
        catch(ConnectException exp)
        {
          JOptionPane.showMessageDialog(null, "Connection Problems...\n"+
                exp.getMessage(), 
                "Connection Error",
                JOptionPane.ERROR_MESSAGE);
        }
        catch(java.sql.SQLException sqlExp)
        {
          JOptionPane.showMessageDialog(null, "SQL Problems....\n"+
                                        sqlExp.getMessage(), 
                                        "SQL Error",
                                        JOptionPane.ERROR_MESSAGE);
        }
        return dao;
      }
    
    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(final Vector sql,
                        final boolean force)
    
    tjc's avatar
    tjc committed
      {
    
    tjc's avatar
    tjc committed
        GmodDAO dao = null;
    
        int ncommit = -1;
    
        final Hashtable featureIdStore = new Hashtable();
    
        boolean useTransactions = false;
    
    tjc's avatar
    tjc committed
        try
        {
    
    tjc's avatar
    tjc committed
          dao = getDAO();
    
          
          if(!force && dao instanceof IBatisDAO)
            useTransactions = true;
          
    
          if(useTransactions)
    
            ((IBatisDAO) dao).startTransaction();
    
            logger4j.debug("START TRANSACTION");
          }
    
          boolean unchanged;
          
          //
          // check feature timestamps have not changed
    
          Vector names_checked = new Vector();
    
    tjc's avatar
    tjc committed
          
          for(int i = 0; i < sql.size(); i++)
    
    tjc's avatar
    tjc committed
          {
    
    tjc's avatar
    tjc committed
            final ChadoTransaction tsn = (ChadoTransaction)sql.get(i);
    
            final Object uniquenames[] = getUniqueNames(tsn);
    
            if(uniquenames == null)
    
    tjc's avatar
    tjc committed
              continue;
    
            
            for(int j=0; j<uniquenames.length; j++)
    
    tjc's avatar
    tjc committed
            {
    
              final String uniquename = (String) uniquenames[j];
              
              if(uniquename == null || names_checked.contains(uniquename))
                continue;
    
              names_checked.add(uniquename);
              final String keyName = tsn.getFeatureKey();
    
    tjc's avatar
    tjc committed
    
    
              unchanged = checkFeatureTimestamp(schema, uniquename, 
    
    tjc's avatar
    tjc committed
                  dao, keyName, featureIdStore, tsn);
    
              if(!unchanged)
              {
                if(useTransactions)
                  ((IBatisDAO) dao).endTransaction();
                return 0;
              }
    
    tjc's avatar
    tjc committed
            }
    
    tjc's avatar
    tjc committed
          final Timestamp ts = new Timestamp(new java.util.Date().getTime());
    
    tjc's avatar
    tjc committed
          //
          // commit to database
          for(ncommit = 0; ncommit < sql.size(); ncommit++)
    
            try
            {
              ChadoTransaction tsn = (ChadoTransaction) sql.get(ncommit);
    
    tjc's avatar
    tjc committed
              commitChadoTransaction(tsn, dao, ts);
    
            }
            catch (RuntimeException re)
            {
              if(!force)
                throw re;
              logger4j.warn(constructExceptionMessage(re, sql, ncommit));
              logger4j.warn("NOW TRYING TO CONTINUE TO COMMIT");
            }
    
    tjc's avatar
    tjc committed
          }
    
    tjc's avatar
    tjc committed
          //
          // update timelastmodified timestamp
          names_checked = new Vector();
    
          for(int i = 0; i < sql.size(); i++)
    
    tjc's avatar
    tjc committed
          {
    
            final ChadoTransaction tsn = (ChadoTransaction) sql.get(i);
            final Object uniquenames[] = getUniqueNames(tsn);
                 
            if(uniquenames == null)
    
    tjc's avatar
    tjc committed
              continue;
    
    tjc's avatar
    tjc committed
            if(tsn.getType() == ChadoTransaction.UPDATE &&
               tsn.getFeatureObject() instanceof Feature)
            {
              for(int j=0; j<uniquenames.length; j++)
                names_checked.add((String) uniquenames[j]);
              continue;  
            }
            
    
            for(int j=0; j<uniquenames.length; j++)
            {
              final String uniquename = (String) uniquenames[j];
              if(uniquename == null || names_checked.contains(uniquename))
                continue;
    
              names_checked.add(uniquename);
    
    tjc's avatar
    tjc committed
    
    
              final Feature feature;
    
              // retieve from featureId store
              if(featureIdStore != null && featureIdStore.containsKey(uniquename))
              {
    
    tjc's avatar
    tjc committed
                Feature f = (Feature) featureIdStore.get(uniquename);
    
    
                feature = new Feature();
    
    tjc's avatar
    tjc committed
                feature.setFeatureId(f.getFeatureId());
    
                feature.setUniqueName(uniquename);
    
    tjc's avatar
    tjc committed
                feature.setObsolete(f.isObsolete());
    
              }
              else
                feature = dao.getFeatureByUniqueName(uniquename, 
                                           tsn.getFeatureKey());
    
    tjc's avatar
    tjc committed
    
    
              if(feature != null)
              {
                feature.setTimeLastModified(ts);
    
                feature.setName("0");  // do not change name
    
                dao.merge(feature);
              }
    
    tjc's avatar
    tjc committed
            }
    
            GFFStreamFeature gff_feature = (GFFStreamFeature) tsn.getGff_feature();
            gff_feature.setLastModified(ts);
    
    tjc's avatar
    tjc committed
    
    
          final String nocommit = System.getProperty("nocommit");
          if( useTransactions && 
              (nocommit == null || nocommit.equals("false")))
    
    tjc's avatar
    tjc committed
            ((IBatisDAO) dao).commitTransaction();
    
            logger4j.debug("TRANSACTION COMPLETE");
    
          else if(useTransactions && 
              (nocommit != null && nocommit.equals("true")))
            logger4j.debug("TRANSACTION NOT COMMITTED : nocommit property set to true");
    
    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
        }
    
        catch (RuntimeException re)
        {
          final String msg = constructExceptionMessage(re, sql, ncommit);
          JOptionPane.showMessageDialog(null, msg,
              "Problems Writing to Database ",
              JOptionPane.ERROR_MESSAGE);
          logger4j.error(msg);
    
          //re.printStackTrace();
    
        }
        finally
        {
          if(useTransactions)
            try
            {
              ((IBatisDAO) dao).endTransaction();
    
              logger4j.debug("END TRANSACTION");
    
            catch(SQLException e){ e.printStackTrace(); }
    
    tjc's avatar
    tjc committed
        
        if(featureIdStore != null)
          featureIdStore.clear();
            
        return ncommit;
      }
      
    
      /**
       * Get the uniquenames involved in a transaction
       * @param tsn
       * @return
       */
      private Object[] getUniqueNames(final ChadoTransaction tsn)
      {
        if(tsn.getGff_feature() == null)
          return null;
        if(tsn.getGff_feature().getSegmentRangeStore() == null ||
    
    tjc's avatar
    tjc committed
           tsn.getGff_feature().getSegmentRangeStore().size() < 2 ||
           tsn.getFeatureObject() instanceof FeatureProp)
    
          return new Object[]{ tsn.getUniquename() };
        else 
          return tsn.getGff_feature().getSegmentRangeStore().keySet().toArray();
      }
      
    
      /**
       * Construct an exeption message from the ChadoTransaction
       * @param re
       * @param sql
       * @param ncommit
       * @return
       */
      private String constructExceptionMessage(final RuntimeException re,
                                               final Vector sql,
                                               final int ncommit)
      {
        String msg = "";
        if(ncommit > -1 && ncommit < sql.size())
        {
          final ChadoTransaction t_failed = (ChadoTransaction)sql.get(ncommit);
          
          if(t_failed.getType() == ChadoTransaction.DELETE)
            msg = "DELETE failed ";
          else if(t_failed.getType() == ChadoTransaction.INSERT)
            msg = "INSERT failed ";
          else if(t_failed.getType() == ChadoTransaction.UPDATE)
            msg = "UPDATE failed ";
            
          if(t_failed.getUniquename() != null)
            msg = msg + "for " + t_failed.getUniquename()+":";
          else if(t_failed.getFeatureObject() != null &&
                  t_failed.getFeatureObject() instanceof Feature)
          {
            final Feature chadoFeature = (Feature)t_failed.getFeatureObject();
            if(chadoFeature.getUniqueName() != null)
              msg = msg + "for " + chadoFeature.getUniqueName() +":";
          }
            
          msg = msg+"\n";
        }
        
        return msg + re.getMessage();  
      }
      
    
    tjc's avatar
    tjc committed
      /**
       * Commit a single chado transaction
       * @param tsn
       * @param dao
       */
      private void commitChadoTransaction(final ChadoTransaction tsn,
    
    tjc's avatar
    tjc committed
                                          final GmodDAO dao,
                                          final Timestamp ts)
    
    tjc's avatar
    tjc committed
      {
        if(tsn.getType() == ChadoTransaction.UPDATE)
        {
          if(tsn.getFeatureObject() instanceof Feature)
          {
            Feature feature = (Feature)tsn.getFeatureObject();
    
    tjc's avatar
    tjc committed
    
    
    tjc's avatar
    tjc committed
            if(feature.getUniqueName() != null)
            {
              final String uniquename;
              if(tsn.getOldUniquename() != null)
                uniquename = (String)tsn.getOldUniquename();
              else
                uniquename = feature.getUniqueName();
              
              Feature old_feature
                  = dao.getFeatureByUniqueName(uniquename, tsn.getFeatureKey());
              
              if(old_feature != null)
                feature.setFeatureId( old_feature.getFeatureId() );
              
              tsn.setOldUniquename(feature.getUniqueName());
            }
    
    tjc's avatar
    tjc committed
            feature.setTimeLastModified(ts);
    
    tjc's avatar
    tjc committed
          }
          dao.merge(tsn.getFeatureObject());
          //dao.updateAttributes(tsn);
        }
        else if(tsn.getType() == ChadoTransaction.INSERT)
        {
          if(tsn.getFeatureObject() instanceof FeatureCvTerm)
            ArtemisUtils.inserFeatureCvTerm(dao, (FeatureCvTerm)tsn.getFeatureObject());
          else
          {
            // set srcfeature_id
            if(tsn.getFeatureObject() instanceof Feature &&
                ((Feature) tsn.getFeatureObject()).getFeatureLoc() != null)
            {
              FeatureLoc featureloc = ((Feature) tsn.getFeatureObject()).getFeatureLoc();
              Feature featureBySrcFeatureId = new Feature();
              featureBySrcFeatureId.setFeatureId(Integer.parseInt(srcFeatureId));
              featureloc.setFeatureBySrcFeatureId(featureBySrcFeatureId);
            }
            dao.persist(tsn.getFeatureObject());
          }
          
        }
        else if(tsn.getType() == ChadoTransaction.DELETE)
        {
          if(tsn.getFeatureObject() instanceof FeatureCvTerm)
            ArtemisUtils.deleteFeatureCvTerm(dao, (FeatureCvTerm)tsn.getFeatureObject());
          else
            dao.delete(tsn.getFeatureObject());
        }
    
    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
       */
    
      public boolean checkFeatureTimestamp(final String schema,
    
    tjc's avatar
    tjc committed
                                           final String uniquename,
    
    tjc's avatar
    tjc committed
                                           final String keyName,
    
    tjc's avatar
    tjc committed
                                           final Hashtable featureIdStore,
                                           final ChadoTransaction tsn)
    
    tjc's avatar
    tjc committed
        final Timestamp timestamp  = tsn.getLastModified();
        final Object featureObject = tsn.getFeatureObject();
        
    
    tjc's avatar
    tjc committed
        final Feature feature = dao.getFeatureByUniqueName(uniquename, keyName);
    
    tjc's avatar
    tjc committed
        if(feature == null)
          return true;
    
    tjc's avatar
    tjc committed
        featureIdStore.put(uniquename, feature);
    
    tjc's avatar
    tjc committed
        
    
        if(featureObject instanceof FeatureProp)
          ((FeatureProp)featureObject).setFeature(feature);
        else if(featureObject instanceof FeatureLoc)
    
    tjc's avatar
    tjc committed
        {
          if(((FeatureLoc)featureObject).getFeatureByFeatureId().getUniqueName().equals(uniquename))
          {
            logger4j.debug("Setting featureId for:"  + uniquename );
            ((FeatureLoc)featureObject).setFeatureByFeatureId(feature);
          }
        }
        
    
    tjc's avatar
    tjc committed
        final Timestamp now = feature.getTimeLastModified();
    
    tjc's avatar
    tjc committed
        if(now != null && timestamp != null)
    
        {
          now.setNanos(0);
          timestamp.setNanos(0);
          
    
          if(now.compareTo(timestamp) != 0)
          {
    
    tjc's avatar
    tjc committed
            final 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
        {
    
          GmodDAO dao;
    
    tjc's avatar
    tjc committed
          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
          Feature feature = new Feature();
    
    tjc's avatar
    tjc committed
          feature.setUniqueName(args[0]);
    
    tjc's avatar
    tjc committed
          List schemas = new Vector();
          schemas.add(args[1]);
    
    tjc's avatar
    tjc committed
          List featureList = new Vector();
    
          featureList.add(dao.getFeatureByUniqueName(args[0], "polypeptide")); 
    
    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 = (Feature)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();
    
            int fmin    = feature.getFeatureLoc().getFmin().intValue() + 1;
            int fmax    = feature.getFeatureLoc().getFmax().intValue();
    
    tjc's avatar
    tjc committed
            String featprop = 
    
    tjc's avatar
    tjc committed
              ((FeatureProp)(new Vector(feature.getFeatureProps()).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);
    
            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.getFeatureId()));
    
    tjc's avatar
    tjc committed
            
    
    tjc's avatar
    tjc committed
    /*      Hashtable synonyms = getAllFeatureSynonyms(dao, null);
    
    tjc's avatar
    tjc committed
            Vector syns = (Vector)synonyms.get(new Integer(feature.getId()));
            for(int j=0; j<syns.size(); j++)
            {
    
    tjc's avatar
    tjc committed
              FeatureSynonym alias = (FeatureSynonym)syns.get(j);
    
    tjc's avatar
    tjc committed
              System.out.print(" "+alias.getSynonym().getCvterm().getName()+