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