748cb72daa301d050856855600c0ff8a0fc9efbf
[jalview.git] / src / jalview / ws / DBRefFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.bin.Cache;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.DBRefSource;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.SequenceFeature;
30 import jalview.datamodel.SequenceI;
31 import jalview.gui.CutAndPasteTransfer;
32 import jalview.gui.DasSourceBrowser;
33 import jalview.gui.Desktop;
34 import jalview.gui.FeatureSettings;
35 import jalview.gui.IProgressIndicator;
36 import jalview.gui.OOMWarning;
37 import jalview.util.DBRefUtils;
38 import jalview.util.MessageManager;
39 import jalview.ws.dbsources.das.api.jalviewSourceI;
40 import jalview.ws.dbsources.das.datamodel.DasSequenceSource;
41 import jalview.ws.seqfetcher.DbSourceProxy;
42
43 import java.util.ArrayList;
44 import java.util.Arrays;
45 import java.util.Enumeration;
46 import java.util.Hashtable;
47 import java.util.List;
48 import java.util.StringTokenizer;
49 import java.util.Vector;
50
51 import uk.ac.ebi.picr.model.UPEntry;
52 import uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator;
53
54 /**
55  * Implements a runnable for validating a sequence against external databases
56  * and then propagating references and features onto the sequence(s)
57  * 
58  * @author $author$
59  * @version $Revision$
60  */
61 public class DBRefFetcher implements Runnable
62 {
63   public interface FetchFinishedListenerI
64   {
65     void finished();
66   }
67
68   SequenceI[] dataset;
69
70   IProgressIndicator progressWindow;
71
72   CutAndPasteTransfer output = new CutAndPasteTransfer();
73
74   StringBuffer sbuffer = new StringBuffer();
75
76   boolean running = false;
77
78   /**
79    * picr client instance
80    */
81   uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
82
83   // This will be a collection of Vectors of sequenceI refs.
84   // The key will be the seq name or accession id of the seq
85   Hashtable<String, Vector<SequenceI>> seqRefs;
86
87   DbSourceProxy[] dbSources;
88
89   SequenceFetcher sfetcher;
90
91   private List<FetchFinishedListenerI> listeners;
92
93   private SequenceI[] alseqs;
94
95   /*
96    * when true - retrieved sequences will be trimmed to cover longest derived
97    * alignment sequence
98    */
99   private boolean trimDsSeqs = true;
100
101   /**
102    * Creates a new DBRefFetcher object and fetches from the currently selected
103    * set of databases, if this is null then it fetches based on feature settings
104    * 
105    * @param seqs
106    *          fetch references for these SequenceI array
107    * @param progressIndicatorFrame
108    *          the frame for progress bar monitoring
109    * @param sources
110    *          array of DbSourceProxy to query references form
111    * @param featureSettings
112    *          FeatureSettings to get alternative DbSourceProxy from
113    * @param isNucleotide
114    *          indicates if the array of SequenceI are Nucleotides or not
115    */
116   public DBRefFetcher(SequenceI[] seqs,
117           IProgressIndicator progressIndicatorFrame,
118           DbSourceProxy[] sources, FeatureSettings featureSettings, boolean isNucleotide)
119   {
120     listeners = new ArrayList<FetchFinishedListenerI>();
121     this.progressWindow = progressIndicatorFrame;
122     alseqs = new SequenceI[seqs.length];
123     SequenceI[] ds = new SequenceI[seqs.length];
124     for (int i = 0; i < seqs.length; i++)
125     {
126       alseqs[i] = seqs[i];
127       if (seqs[i].getDatasetSequence() != null)
128       {
129         ds[i] = seqs[i].getDatasetSequence();
130       }
131       else
132       {
133         ds[i] = seqs[i];
134       }
135     }
136     this.dataset = ds;
137     // TODO Jalview 2.5 lots of this code should be in the gui package!
138     sfetcher = jalview.gui.SequenceFetcher
139             .getSequenceFetcherSingleton(progressIndicatorFrame);
140     // set default behaviour for transferring excess sequence data to the
141     // dataset
142     trimDsSeqs = Cache.getDefault("TRIM_FETCHED_DATASET_SEQS", true);
143     if (sources == null)
144     {
145       setDatabaseSources(featureSettings, isNucleotide);
146     }
147     else
148     {
149       // we assume the caller knows what they're doing and ensured that all the
150       // db source names are valid
151       dbSources = sources;
152     }
153   }
154
155   /**
156    * Helper method to configure the list of database sources to query
157    * 
158    * @param featureSettings
159    * @param forNucleotide
160    */
161   void setDatabaseSources(FeatureSettings featureSettings,
162           boolean forNucleotide)
163   {
164     // af.featureSettings_actionPerformed(null);
165     String[] defdb = null;
166     List<DbSourceProxy> selsources = new ArrayList<DbSourceProxy>();
167     Vector<jalviewSourceI> dasselsrc = (featureSettings != null) ? featureSettings
168             .getSelectedSources() : new DasSourceBrowser()
169             .getSelectedSources();
170
171     for (jalviewSourceI src : dasselsrc)
172     {
173       List<DbSourceProxy> sp = src.getSequenceSourceProxies();
174       if (sp != null)
175       {
176         selsources.addAll(sp);
177         if (sp.size() > 1)
178         {
179           Cache.log.debug("Added many Db Sources for :" + src.getTitle());
180         }
181       }
182     }
183     // select appropriate databases based on alignFrame context.
184     if (forNucleotide)
185     {
186       defdb = DBRefSource.DNACODINGDBS;
187     }
188     else
189     {
190       defdb = DBRefSource.PROTEINDBS;
191     }
192     List<DbSourceProxy> srces = new ArrayList<DbSourceProxy>();
193     for (String ddb : defdb)
194     {
195       List<DbSourceProxy> srcesfordb = sfetcher.getSourceProxy(ddb);
196       if (srcesfordb != null)
197       {
198         for (DbSourceProxy src : srcesfordb)
199         {
200           if (!srces.contains(src))
201           {
202             srces.addAll(srcesfordb);
203           }
204         }
205       }
206     }
207     // append the PDB data source, since it is 'special', catering for both
208     // nucleotide and protein
209     // srces.addAll(sfetcher.getSourceProxy(DBRefSource.PDB));
210
211     srces.addAll(selsources);
212     dbSources = srces.toArray(new DbSourceProxy[srces.size()]);
213   }
214
215   /**
216    * Constructor with only sequences provided
217    * 
218    * @param sequences
219    */
220   public DBRefFetcher(SequenceI[] sequences)
221   {
222     this(sequences, null, null, null, false);
223   }
224
225   /**
226    * Add a listener to be notified when sequence fetching is complete
227    * 
228    * @param l
229    */
230   public void addListener(FetchFinishedListenerI l)
231   {
232     listeners.add(l);
233   }
234
235   /**
236    * retrieve all the das sequence sources and add them to the list of db
237    * sources to retrieve from
238    */
239   public void appendAllDasSources()
240   {
241     if (dbSources == null)
242     {
243       dbSources = new DbSourceProxy[0];
244     }
245     // append additional sources
246     DbSourceProxy[] otherdb = sfetcher
247             .getDbSourceProxyInstances(DasSequenceSource.class);
248     if (otherdb != null && otherdb.length > 0)
249     {
250       DbSourceProxy[] newsrc = new DbSourceProxy[dbSources.length
251               + otherdb.length];
252       System.arraycopy(dbSources, 0, newsrc, 0, dbSources.length);
253       System.arraycopy(otherdb, 0, newsrc, dbSources.length, otherdb.length);
254       dbSources = newsrc;
255     }
256   }
257
258   /**
259    * start the fetcher thread
260    * 
261    * @param waitTillFinished
262    *          true to block until the fetcher has finished
263    */
264   public void fetchDBRefs(boolean waitTillFinished)
265   {
266     // TODO can we not simply write
267     // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
268
269     Thread thread = new Thread(this);
270     thread.start();
271     running = true;
272
273     if (waitTillFinished)
274     {
275       while (running)
276       {
277         try
278         {
279           Thread.sleep(500);
280         } catch (Exception ex)
281         {
282         }
283       }
284     }
285   }
286
287   /**
288    * The sequence will be added to a vector of sequences belonging to key which
289    * could be either seq name or dbref id
290    * 
291    * @param seq
292    *          SequenceI
293    * @param key
294    *          String
295    */
296   void addSeqId(SequenceI seq, String key)
297   {
298     key = key.toUpperCase();
299
300     Vector<SequenceI> seqs;
301     if (seqRefs.containsKey(key))
302     {
303       seqs = seqRefs.get(key);
304
305       if (seqs != null && !seqs.contains(seq))
306       {
307         seqs.addElement(seq);
308       }
309       else if (seqs == null)
310       {
311         seqs = new Vector<SequenceI>();
312         seqs.addElement(seq);
313       }
314
315     }
316     else
317     {
318       seqs = new Vector<SequenceI>();
319       seqs.addElement(seq);
320     }
321
322     seqRefs.put(key, seqs);
323   }
324
325   /**
326    * DOCUMENT ME!
327    */
328   @Override
329   public void run()
330   {
331     if (dbSources == null)
332     {
333       throw new Error(
334               MessageManager
335                       .getString("error.implementation_error_must_init_dbsources"));
336     }
337     running = true;
338     long startTime = System.currentTimeMillis();
339     if (progressWindow != null)
340     {
341       progressWindow.setProgressBar(
342               MessageManager.getString("status.fetching_db_refs"),
343             startTime);
344     }
345     try
346     {
347       if (Cache.getDefault("DBREFFETCH_USEPICR", false))
348       {
349         picrClient = new AccessionMapperServiceLocator()
350                 .getAccessionMapperPort();
351       }
352     } catch (Exception e)
353     {
354       System.err.println("Couldn't locate PICR service instance.\n");
355       e.printStackTrace();
356     }
357
358     Vector<SequenceI> sdataset = new Vector<SequenceI>(
359             Arrays.asList(dataset));
360
361     int db = 0;
362     while (sdataset.size() > 0 && db < dbSources.length)
363     {
364       int maxqlen = 1; // default number of queries made at one time
365       System.out.println("Verifying against " + dbSources[db].getDbName());
366
367       // iterate through db for each remaining un-verified sequence
368       SequenceI[] currSeqs = new SequenceI[sdataset.size()];
369       sdataset.copyInto(currSeqs);// seqs that are to be validated against
370       // dbSources[db]
371       Vector<String> queries = new Vector<String>(); // generated queries curSeq
372       seqRefs = new Hashtable<String, Vector<SequenceI>>();
373
374       int seqIndex = 0;
375
376       DbSourceProxy dbsource = dbSources[db];
377       // for moment, we dumbly iterate over all retrieval sources for a
378       // particular database
379       // TODO: introduce multithread multisource queries and logic to remove a
380       // query from other sources if any source for a database returns a
381       // record
382       maxqlen = dbsource.getMaximumQueryCount();
383
384       while (queries.size() > 0 || seqIndex < currSeqs.length)
385       {
386         if (queries.size() > 0)
387         {
388           // Still queries to make for current seqIndex
389           StringBuffer queryString = new StringBuffer("");
390           int numq = 0;
391           int nqSize = (maxqlen > queries.size()) ? queries
392                   .size() : maxqlen;
393
394           while (queries.size() > 0 && numq < nqSize)
395           {
396             String query = queries.elementAt(0);
397             if (dbsource.isValidReference(query))
398             {
399               queryString.append((numq == 0) ? "" : dbsource
400                       .getAccessionSeparator());
401               queryString.append(query);
402               numq++;
403             }
404             // remove the extracted query string
405             queries.removeElementAt(0);
406           }
407           // make the queries and process the response
408           AlignmentI retrieved = null;
409           try
410           {
411             if (Cache.log.isDebugEnabled())
412             {
413               Cache.log.debug("Querying " + dbsource.getDbName()
414                       + " with : '" + queryString.toString() + "'");
415             }
416             retrieved = dbsource.getSequenceRecords(queryString.toString());
417           } catch (Exception ex)
418           {
419             ex.printStackTrace();
420           } catch (OutOfMemoryError err)
421           {
422             new OOMWarning("retrieving database references ("
423                     + queryString.toString() + ")", err);
424           }
425           if (retrieved != null)
426           {
427             transferReferences(sdataset, dbsource.getDbSource(), retrieved,
428                     trimDsSeqs);
429           }
430         }
431         else
432         {
433           // make some more strings for use as queries
434           for (int i = 0; (seqIndex < dataset.length) && (i < 50); seqIndex++, i++)
435           {
436             SequenceI sequence = dataset[seqIndex];
437             DBRefEntry[] uprefs = DBRefUtils.selectRefs(
438                     sequence.getDBRefs(),
439                     new String[] { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
440             // });
441             // check for existing dbrefs to use
442             if (uprefs != null && uprefs.length > 0)
443             {
444               for (int j = 0; j < uprefs.length; j++)
445               {
446                 addSeqId(sequence, uprefs[j].getAccessionId());
447                 queries.addElement(uprefs[j].getAccessionId().toUpperCase());
448               }
449             }
450             else
451             {
452               // generate queries from sequence ID string
453               StringTokenizer st = new StringTokenizer(sequence.getName(),
454                       "|");
455               while (st.hasMoreTokens())
456               {
457                 String token = st.nextToken();
458                 UPEntry[] presp = null;
459                 if (picrClient != null)
460                 {
461                   // resolve the string against PICR to recover valid IDs
462                   try
463                   {
464                     presp = picrClient
465                             .getUPIForAccession(token, null,
466                                     picrClient.getMappedDatabaseNames(),
467                                     null, true);
468                   } catch (Exception e)
469                   {
470                     System.err.println("Exception with Picr for '" + token
471                             + "'\n");
472                     e.printStackTrace();
473                   }
474                 }
475                 if (presp != null && presp.length > 0)
476                 {
477                   for (int id = 0; id < presp.length; id++)
478                   {
479                     // construct sequences from response if sequences are
480                     // present, and do a transferReferences
481                     // otherwise transfer non sequence x-references directly.
482                   }
483                   System.out
484                           .println("Validated ID against PICR... (for what its worth):"
485                                   + token);
486                   addSeqId(sequence, token);
487                   queries.addElement(token.toUpperCase());
488                 }
489                 else
490                 {
491                   // if ()
492                   // System.out.println("Not querying source with token="+token+"\n");
493                   addSeqId(sequence, token);
494                   queries.addElement(token.toUpperCase());
495                 }
496               }
497             }
498           }
499         }
500       }
501       // advance to next database
502       db++;
503     } // all databases have been queried
504     if (sbuffer.length() > 0)
505     {
506       output.setText(MessageManager
507               .getString("label.your_sequences_have_been_verified")
508               + sbuffer.toString());
509       Desktop.addInternalFrame(output,
510               MessageManager.getString("label.sequence_names_updated"),
511               600, 300);
512       // The above is the dataset, we must now find out the index
513       // of the viewed sequence
514
515     }
516     if (progressWindow != null)
517     {
518       progressWindow.setProgressBar(
519               MessageManager.getString("label.dbref_search_completed"),
520               startTime);
521     }
522
523     for (FetchFinishedListenerI listener : listeners)
524     {
525       listener.finished();
526     }
527     running = false;
528   }
529
530   /**
531    * Verify local sequences in seqRefs against the retrieved sequence database
532    * records.
533    * 
534    * @param trimDatasetSeqs
535    * 
536    */
537   void transferReferences(Vector<SequenceI> sdataset, String dbSource,
538           AlignmentI retrievedAl, boolean trimDatasetSeqs)
539   {
540     // System.out.println("trimming ? " + trimDatasetSeqs);
541     if (retrievedAl == null || retrievedAl.getHeight() == 0)
542     {
543       return;
544     }
545     SequenceI[] retrieved = recoverDbSequences(retrievedAl
546             .getSequencesArray());
547     SequenceI sequence = null;
548     boolean transferred = false;
549     StringBuilder messages = new StringBuilder(64);
550
551     for (SequenceI entry : retrieved)
552     {
553       // Work out which sequences this sequence matches,
554       // taking into account all accessionIds and names in the file
555       Vector<SequenceI> sequenceMatches = new Vector<SequenceI>();
556       // look for corresponding accession ids
557       DBRefEntry[] entryRefs = jalview.util.DBRefUtils.selectRefs(
558               entry.getDBRefs(), new String[] { dbSource });
559       if (entryRefs == null)
560       {
561         System.err
562                 .println("Dud dbSource string ? no entryrefs selected for "
563                         + dbSource + " on " + entry.getName());
564         continue;
565       }
566       for (int j = 0; j < entryRefs.length; j++)
567       {
568         String accessionId = entryRefs[j].getAccessionId();
569         // match up on accessionId
570         if (seqRefs.containsKey(accessionId.toUpperCase()))
571         {
572           Vector<SequenceI> seqs = seqRefs.get(accessionId);
573           for (int jj = 0; jj < seqs.size(); jj++)
574           {
575             sequence = seqs.elementAt(jj);
576             if (!sequenceMatches.contains(sequence))
577             {
578               sequenceMatches.addElement(sequence);
579             }
580           }
581         }
582       }
583       if (sequenceMatches.isEmpty())
584       {
585         // failed to match directly on accessionId==query so just compare all
586         // sequences to entry
587         Enumeration<String> e = seqRefs.keys();
588         while (e.hasMoreElements())
589         {
590           Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
591           if (sqs != null && sqs.size() > 0)
592           {
593             Enumeration<SequenceI> sqe = sqs.elements();
594             while (sqe.hasMoreElements())
595             {
596               sequenceMatches.addElement(sqe.nextElement());
597             }
598           }
599         }
600       }
601       // look for corresponding names
602       // this is uniprot specific ?
603       // could be useful to extend this so we try to find any 'significant'
604       // information in common between two sequence objects.
605       /*
606        * DBRefEntry[] entryRefs =
607        * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
608        * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
609        * name = entry.getName().elementAt(j).toString(); if
610        * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
611        * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
612        * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
613        * sequenceMatches.addElement(sequence); } } } }
614        */
615       // sequenceMatches now contains the set of all sequences associated with
616       // the returned db record
617       String entrySeq = entry.getSequenceAsString().toUpperCase();
618       for (int m = 0; m < sequenceMatches.size(); m++)
619       {
620         sequence = sequenceMatches.elementAt(m);
621         // only update start and end positions and shift features if there are
622         // no existing references
623         // TODO: test for legacy where uniprot or EMBL refs exist but no
624         // mappings are made (but content matches retrieved set)
625         boolean updateRefFrame = sequence.getDBRefs() == null
626                 || sequence.getDBRefs().length == 0;
627         // TODO:
628         // verify sequence against the entry sequence
629
630         String nonGapped = AlignSeq.extractGaps("-. ",
631                 sequence.getSequenceAsString()).toUpperCase();
632
633         int absStart = entrySeq.indexOf(nonGapped);
634         Mapping mp;
635
636         final int sequenceStart = sequence.getStart();
637         if (absStart == -1)
638         {
639           // couldn't find local sequence in sequence from database, so check if
640           // the database sequence is a subsequence of local sequence
641           absStart = nonGapped.indexOf(entrySeq);
642           if (absStart == -1)
643           {
644             // verification failed. couldn't find any relationship between
645             // entrySeq and local sequence
646             messages.append(sequence.getName()
647                     + " Sequence not 100% match with " + entry.getName()
648                     + "\n");
649             continue;
650           }
651           /*
652            * found match for the whole of the database sequence within the local
653            * sequence's reference frame. 
654            */
655           transferred = true;
656           sbuffer.append(sequence.getName() + " has " + absStart
657                   + " prefixed residues compared to " + entry.getName()
658                   + "\n");
659
660           /*
661            * So create a mapping to the external entry from the matching region of 
662            * the local sequence, and leave local start/end untouched. 
663            */
664           mp = new Mapping(null, new int[] { sequenceStart + absStart,
665               sequenceStart + absStart + entrySeq.length() - 1 }, new int[]
666           { entry.getStart(), entry.getStart() + entrySeq.length() - 1 },
667                   1, 1);
668           updateRefFrame = false;
669         }
670         else
671         {
672           /*
673            * found a match for the local sequence within sequence from 
674            * the external database 
675            */
676           transferred = true;
677
678           // update start and end of local sequence to place it in entry's
679           // reference frame.
680           // apply identity map map from whole of local sequence to matching
681           // region of database
682           // sequence
683           mp = null; // Mapping.getIdentityMap();
684           // new Mapping(null,
685           // new int[] { absStart+sequence.getStart(),
686           // absStart+sequence.getStart()+entrySeq.length()-1},
687           // new int[] { entry.getStart(), entry.getEnd() }, 1, 1);
688           // relocate local features for updated start
689
690           if (updateRefFrame)
691           {
692             if (sequence.getSequenceFeatures() != null)
693             {
694               /*
695                * relocate existing sequence features by offset
696                */
697               SequenceFeature[] sf = sequence.getSequenceFeatures();
698               int start = sequenceStart;
699               int end = sequence.getEnd();
700               int startShift = 1 - absStart - start; // how much the features
701                                                      // are
702               // to be shifted by
703               for (int sfi = 0; sfi < sf.length; sfi++)
704               {
705                 if (sf[sfi].getBegin() >= start && sf[sfi].getEnd() <= end)
706                 {
707                   // shift feature along by absstart
708                   sf[sfi].setBegin(sf[sfi].getBegin() + startShift);
709                   sf[sfi].setEnd(sf[sfi].getEnd() + startShift);
710                 }
711               }
712             }
713           }
714         }
715
716         System.out.println("Adding dbrefs to " + sequence.getName()
717                 + " from " + dbSource + " sequence : " + entry.getName());
718         sequence.transferAnnotation(entry, mp);
719
720         absStart += entry.getStart();
721         int absEnd = absStart + nonGapped.length() - 1;
722         if (!trimDatasetSeqs)
723         {
724           // insert full length sequence from record
725           sequence.setSequence(entry.getSequenceAsString());
726           sequence.setStart(entry.getStart());
727         }
728         if (updateRefFrame)
729         {
730           // finally, update local sequence reference frame if we're allowed
731           if (trimDatasetSeqs)
732           {
733             // just fix start/end
734             sequence.setStart(absStart);
735             sequence.setEnd(absEnd);
736           }
737           // search for alignment sequences to update coordinate frame for
738           for (int alsq = 0; alsq < alseqs.length; alsq++)
739           {
740             if (alseqs[alsq].getDatasetSequence() == sequence)
741             {
742               String ngAlsq = AlignSeq.extractGaps("-. ",
743                       alseqs[alsq].getSequenceAsString()).toUpperCase();
744               int oldstrt = alseqs[alsq].getStart();
745               alseqs[alsq].setStart(sequence.getSequenceAsString()
746                       .toUpperCase().indexOf(ngAlsq)
747                       + sequence.getStart());
748               if (oldstrt != alseqs[alsq].getStart())
749               {
750                 alseqs[alsq].setEnd(ngAlsq.length()
751                         + alseqs[alsq].getStart() - 1);
752               }
753             }
754           }
755           // TODO: search for all other references to this dataset sequence, and
756           // update start/end
757           // TODO: update all AlCodonMappings which involve this alignment
758           // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
759           // demo)
760         }
761         // and remove it from the rest
762         // TODO: decide if we should remove annotated sequence from set
763         sdataset.remove(sequence);
764         // TODO: should we make a note of sequences that have received new DB
765         // ids, so we can query all enabled DAS servers for them ?
766       }
767     }
768     if (!transferred)
769     {
770       // report the ID/sequence mismatches
771       sbuffer.append(messages);
772     }
773   }
774
775   /**
776    * loop thru and collect additional sequences in Map.
777    * 
778    * @param sequencesArray
779    * @return
780    */
781   private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
782   {
783     Vector<SequenceI> nseq = new Vector<SequenceI>();
784     for (int i = 0; sequencesArray != null && i < sequencesArray.length; i++)
785     {
786       nseq.addElement(sequencesArray[i]);
787       DBRefEntry[] dbr = sequencesArray[i].getDBRefs();
788       Mapping map = null;
789       for (int r = 0; (dbr != null) && r < dbr.length; r++)
790       {
791         if ((map = dbr[r].getMap()) != null)
792         {
793           if (map.getTo() != null && !nseq.contains(map.getTo()))
794           {
795             nseq.addElement(map.getTo());
796           }
797         }
798       }
799     }
800     if (nseq.size() > 0)
801     {
802       sequencesArray = new SequenceI[nseq.size()];
803       nseq.toArray(sequencesArray);
804     }
805     return sequencesArray;
806   }
807 }