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