JAL-2826 added action performed for hiding collapsed sequences
[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.DasSourceBrowser;
32 import jalview.gui.Desktop;
33 import jalview.gui.FeatureSettings;
34 import jalview.gui.IProgressIndicator;
35 import jalview.gui.OOMWarning;
36 import jalview.util.DBRefUtils;
37 import jalview.util.MessageManager;
38 import jalview.ws.dbsources.das.api.jalviewSourceI;
39 import jalview.ws.dbsources.das.datamodel.DasSequenceSource;
40 import jalview.ws.seqfetcher.DbSourceProxy;
41
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Enumeration;
45 import java.util.Hashtable;
46 import java.util.List;
47 import java.util.StringTokenizer;
48 import java.util.Vector;
49
50 import uk.ac.ebi.picr.model.UPEntry;
51 import uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperServiceLocator;
52
53 /**
54  * Implements a runnable for validating a sequence against external databases
55  * and then propagating references and features onto the sequence(s)
56  * 
57  * @author $author$
58  * @version $Revision$
59  */
60 public class DBRefFetcher implements Runnable
61 {
62   private static final String NEWLINE = System.lineSeparator();
63
64   public interface FetchFinishedListenerI
65   {
66     void finished();
67   }
68
69   SequenceI[] dataset;
70
71   IProgressIndicator progressWindow;
72
73   CutAndPasteTransfer output = new CutAndPasteTransfer();
74
75   boolean running = false;
76
77   /**
78    * picr client instance
79    */
80   uk.ac.ebi.www.picr.AccessionMappingService.AccessionMapperInterface picrClient = null;
81
82   // This will be a collection of Vectors of sequenceI refs.
83   // The key will be the seq name or accession id of the seq
84   Hashtable<String, Vector<SequenceI>> seqRefs;
85
86   DbSourceProxy[] dbSources;
87
88   SequenceFetcher sfetcher;
89
90   private List<FetchFinishedListenerI> listeners;
91
92   private SequenceI[] alseqs;
93
94   /*
95    * when true - retrieved sequences will be trimmed to cover longest derived
96    * alignment sequence
97    */
98   private boolean trimDsSeqs = true;
99
100   /**
101    * Creates a new DBRefFetcher object and fetches from the currently selected
102    * set of databases, if this is null then it fetches based on feature settings
103    * 
104    * @param seqs
105    *          fetch references for these SequenceI array
106    * @param progressIndicatorFrame
107    *          the frame for progress bar monitoring
108    * @param sources
109    *          array of DbSourceProxy to query references form
110    * @param featureSettings
111    *          FeatureSettings to get alternative DbSourceProxy from
112    * @param isNucleotide
113    *          indicates if the array of SequenceI are Nucleotides or not
114    */
115   public DBRefFetcher(SequenceI[] seqs,
116           IProgressIndicator progressIndicatorFrame,
117           DbSourceProxy[] sources, FeatureSettings featureSettings,
118           boolean isNucleotide)
119   {
120     listeners = new ArrayList<>();
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<>();
167     Vector<jalviewSourceI> dasselsrc = (featureSettings != null)
168             ? featureSettings.getSelectedSources()
169             : new DasSourceBrowser().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<>();
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,
254               otherdb.length);
255       dbSources = newsrc;
256     }
257   }
258
259   /**
260    * start the fetcher thread
261    * 
262    * @param waitTillFinished
263    *          true to block until the fetcher has finished
264    */
265   public void fetchDBRefs(boolean waitTillFinished)
266   {
267     // TODO can we not simply write
268     // if (waitTillFinished) { run(); } else { new Thread(this).start(); }
269
270     Thread thread = new Thread(this, "FetchDBRef");
271     thread.start();
272     running = true;
273
274     if (waitTillFinished)
275     {
276       while (running)
277       {
278         try
279         {
280           Thread.sleep(500);
281         } catch (Exception ex)
282         {
283         }
284       }
285     }
286   }
287
288   /**
289    * The sequence will be added to a vector of sequences belonging to key which
290    * could be either seq name or dbref id
291    * 
292    * @param seq
293    *          SequenceI
294    * @param key
295    *          String
296    */
297   void addSeqId(SequenceI seq, String key)
298   {
299     key = key.toUpperCase();
300
301     Vector<SequenceI> seqs;
302     if (seqRefs.containsKey(key))
303     {
304       seqs = seqRefs.get(key);
305
306       if (seqs != null && !seqs.contains(seq))
307       {
308         seqs.addElement(seq);
309       }
310       else if (seqs == null)
311       {
312         seqs = new Vector<>();
313         seqs.addElement(seq);
314       }
315
316     }
317     else
318     {
319       seqs = new Vector<>();
320       seqs.addElement(seq);
321     }
322
323     seqRefs.put(key, seqs);
324   }
325
326   /**
327    * DOCUMENT ME!
328    */
329   @Override
330   public void run()
331   {
332     if (dbSources == null)
333     {
334       throw new Error(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<>(
359             Arrays.asList(dataset));
360     List<String> warningMessages = new ArrayList<>();
361
362     int db = 0;
363     while (sdataset.size() > 0 && db < dbSources.length)
364     {
365       int maxqlen = 1; // default number of queries made at one time
366       System.out.println("Verifying against " + dbSources[db].getDbName());
367
368       // iterate through db for each remaining un-verified sequence
369       SequenceI[] currSeqs = new SequenceI[sdataset.size()];
370       sdataset.copyInto(currSeqs);// seqs that are to be validated against
371       // dbSources[db]
372       Vector<String> queries = new Vector<>(); // generated queries curSeq
373       seqRefs = new Hashtable<>();
374
375       int seqIndex = 0;
376
377       DbSourceProxy dbsource = dbSources[db];
378       // for moment, we dumbly iterate over all retrieval sources for a
379       // particular database
380       // TODO: introduce multithread multisource queries and logic to remove a
381       // query from other sources if any source for a database returns a
382       // record
383       maxqlen = dbsource.getMaximumQueryCount();
384
385       while (queries.size() > 0 || seqIndex < currSeqs.length)
386       {
387         if (queries.size() > 0)
388         {
389           // Still queries to make for current seqIndex
390           StringBuffer queryString = new StringBuffer("");
391           int numq = 0;
392           int nqSize = (maxqlen > queries.size()) ? queries.size()
393                   : maxqlen;
394
395           while (queries.size() > 0 && numq < nqSize)
396           {
397             String query = queries.elementAt(0);
398             if (dbsource.isValidReference(query))
399             {
400               queryString.append(
401                       (numq == 0) ? "" : dbsource.getAccessionSeparator());
402               queryString.append(query);
403               numq++;
404             }
405             // remove the extracted query string
406             queries.removeElementAt(0);
407           }
408           // make the queries and process the response
409           AlignmentI retrieved = null;
410           try
411           {
412             if (Cache.log.isDebugEnabled())
413             {
414               Cache.log.debug("Querying " + dbsource.getDbName()
415                       + " with : '" + queryString.toString() + "'");
416             }
417             retrieved = dbsource.getSequenceRecords(queryString.toString());
418           } catch (Exception ex)
419           {
420             ex.printStackTrace();
421           } catch (OutOfMemoryError err)
422           {
423             new OOMWarning("retrieving database references ("
424                     + queryString.toString() + ")", err);
425           }
426           if (retrieved != null)
427           {
428             transferReferences(sdataset, dbsource.getDbSource(), retrieved,
429                     trimDsSeqs, warningMessages);
430           }
431         }
432         else
433         {
434           // make some more strings for use as queries
435           for (int i = 0; (seqIndex < dataset.length)
436                   && (i < 50); seqIndex++, i++)
437           {
438             SequenceI sequence = dataset[seqIndex];
439             DBRefEntry[] uprefs = DBRefUtils
440                     .selectRefs(sequence.getDBRefs(), new String[]
441                     { dbsource.getDbSource() }); // jalview.datamodel.DBRefSource.UNIPROT
442             // });
443             // check for existing dbrefs to use
444             if (uprefs != null && uprefs.length > 0)
445             {
446               for (int j = 0; j < uprefs.length; j++)
447               {
448                 addSeqId(sequence, uprefs[j].getAccessionId());
449                 queries.addElement(
450                         uprefs[j].getAccessionId().toUpperCase());
451               }
452             }
453             else
454             {
455               // generate queries from sequence ID string
456               StringTokenizer st = new StringTokenizer(sequence.getName(),
457                       "|");
458               while (st.hasMoreTokens())
459               {
460                 String token = st.nextToken();
461                 UPEntry[] presp = null;
462                 if (picrClient != null)
463                 {
464                   // resolve the string against PICR to recover valid IDs
465                   try
466                   {
467                     presp = picrClient.getUPIForAccession(token, null,
468                             picrClient.getMappedDatabaseNames(), null,
469                             true);
470                   } catch (Exception e)
471                   {
472                     System.err.println(
473                             "Exception with Picr for '" + token + "'\n");
474                     e.printStackTrace();
475                   }
476                 }
477                 if (presp != null && presp.length > 0)
478                 {
479                   for (int id = 0; id < presp.length; id++)
480                   {
481                     // construct sequences from response if sequences are
482                     // present, and do a transferReferences
483                     // otherwise transfer non sequence x-references directly.
484                   }
485                   System.out.println(
486                           "Validated ID against PICR... (for what its worth):"
487                                   + token);
488                   addSeqId(sequence, token);
489                   queries.addElement(token.toUpperCase());
490                 }
491                 else
492                 {
493                   // if ()
494                   // System.out.println("Not querying source with
495                   // token="+token+"\n");
496                   addSeqId(sequence, token);
497                   queries.addElement(token.toUpperCase());
498                 }
499               }
500             }
501           }
502         }
503       }
504       // advance to next database
505       db++;
506     } // all databases have been queried
507     if (!warningMessages.isEmpty())
508     {
509       StringBuilder sb = new StringBuilder(warningMessages.size() * 30);
510       sb.append(MessageManager
511               .getString("label.your_sequences_have_been_verified"));
512       for (String msg : warningMessages)
513       {
514         sb.append(msg).append(NEWLINE);
515       }
516       output.setText(sb.toString());
517
518       Desktop.addInternalFrame(output,
519               MessageManager.getString("label.sequences_updated"), 600,
520               300);
521       // The above is the dataset, we must now find out the index
522       // of the viewed sequence
523
524     }
525     if (progressWindow != null)
526     {
527       progressWindow.setProgressBar(
528               MessageManager.getString("label.dbref_search_completed"),
529               startTime);
530     }
531
532     for (FetchFinishedListenerI listener : listeners)
533     {
534       listener.finished();
535     }
536     running = false;
537   }
538
539   /**
540    * Verify local sequences in seqRefs against the retrieved sequence database
541    * records. Returns true if any sequence was modified as a result (start/end
542    * changed and/or sequence enlarged), else false.
543    * 
544    * @param sdataset
545    *          dataset sequences we are retrieving for
546    * @param dbSource
547    *          database source we are retrieving from
548    * @param retrievedAl
549    *          retrieved sequences as alignment
550    * @param trimDatasetSeqs
551    *          if true, sequences will not be enlarged to match longer retrieved
552    *          sequences, only their start/end adjusted
553    * @param warningMessages
554    *          a list of messages to add to
555    */
556   boolean transferReferences(Vector<SequenceI> sdataset, String dbSource,
557           AlignmentI retrievedAl, boolean trimDatasetSeqs,
558           List<String> warningMessages)
559   {
560     // System.out.println("trimming ? " + trimDatasetSeqs);
561     if (retrievedAl == null || retrievedAl.getHeight() == 0)
562     {
563       return false;
564     }
565
566     boolean modified = false;
567     SequenceI[] retrieved = recoverDbSequences(
568             retrievedAl.getSequencesArray());
569     SequenceI sequence = null;
570
571     for (SequenceI retrievedSeq : retrieved)
572     {
573       // Work out which sequences this sequence matches,
574       // taking into account all accessionIds and names in the file
575       Vector<SequenceI> sequenceMatches = new Vector<>();
576       // look for corresponding accession ids
577       DBRefEntry[] entryRefs = DBRefUtils
578               .selectRefs(retrievedSeq.getDBRefs(), new String[]
579               { dbSource });
580       if (entryRefs == null)
581       {
582         System.err
583                 .println("Dud dbSource string ? no entryrefs selected for "
584                         + dbSource + " on " + retrievedSeq.getName());
585         continue;
586       }
587       for (int j = 0; j < entryRefs.length; j++)
588       {
589         String accessionId = entryRefs[j].getAccessionId();
590         // match up on accessionId
591         if (seqRefs.containsKey(accessionId.toUpperCase()))
592         {
593           Vector<SequenceI> seqs = seqRefs.get(accessionId);
594           for (int jj = 0; jj < seqs.size(); jj++)
595           {
596             sequence = seqs.elementAt(jj);
597             if (!sequenceMatches.contains(sequence))
598             {
599               sequenceMatches.addElement(sequence);
600             }
601           }
602         }
603       }
604       if (sequenceMatches.isEmpty())
605       {
606         // failed to match directly on accessionId==query so just compare all
607         // sequences to entry
608         Enumeration<String> e = seqRefs.keys();
609         while (e.hasMoreElements())
610         {
611           Vector<SequenceI> sqs = seqRefs.get(e.nextElement());
612           if (sqs != null && sqs.size() > 0)
613           {
614             Enumeration<SequenceI> sqe = sqs.elements();
615             while (sqe.hasMoreElements())
616             {
617               sequenceMatches.addElement(sqe.nextElement());
618             }
619           }
620         }
621       }
622       // look for corresponding names
623       // this is uniprot specific ?
624       // could be useful to extend this so we try to find any 'significant'
625       // information in common between two sequence objects.
626       /*
627        * DBRefEntry[] entryRefs =
628        * jalview.util.DBRefUtils.selectRefs(entry.getDBRef(), new String[] {
629        * dbSource }); for (int j = 0; j < entry.getName().size(); j++) { String
630        * name = entry.getName().elementAt(j).toString(); if
631        * (seqRefs.containsKey(name)) { Vector seqs = (Vector) seqRefs.get(name);
632        * for (int jj = 0; jj < seqs.size(); jj++) { sequence = (SequenceI)
633        * seqs.elementAt(jj); if (!sequenceMatches.contains(sequence)) {
634        * sequenceMatches.addElement(sequence); } } } }
635        */
636       // sequenceMatches now contains the set of all sequences associated with
637       // the returned db record
638       final String retrievedSeqString = retrievedSeq.getSequenceAsString();
639       String entrySeq = retrievedSeqString.toUpperCase();
640       for (int m = 0; m < sequenceMatches.size(); m++)
641       {
642         sequence = sequenceMatches.elementAt(m);
643         // only update start and end positions and shift features if there are
644         // no existing references
645         // TODO: test for legacy where uniprot or EMBL refs exist but no
646         // mappings are made (but content matches retrieved set)
647         boolean updateRefFrame = sequence.getDBRefs() == null
648                 || sequence.getDBRefs().length == 0;
649         // TODO:
650         // verify sequence against the entry sequence
651
652         Mapping mp;
653         final int sequenceStart = sequence.getStart();
654
655         boolean remoteEnclosesLocal = false;
656         String nonGapped = AlignSeq
657                 .extractGaps("-. ", sequence.getSequenceAsString())
658                 .toUpperCase();
659         int absStart = entrySeq.indexOf(nonGapped);
660         if (absStart == -1)
661         {
662           // couldn't find local sequence in sequence from database, so check if
663           // the database sequence is a subsequence of local sequence
664           absStart = nonGapped.indexOf(entrySeq);
665           if (absStart == -1)
666           {
667             // verification failed. couldn't find any relationship between
668             // entrySeq and local sequence
669             // messages suppressed as many-to-many matches are confusing
670             // String msg = sequence.getName()
671             // + " Sequence not 100% match with "
672             // + retrievedSeq.getName();
673             // addWarningMessage(warningMessages, msg);
674             continue;
675           }
676           /*
677            * retrieved sequence is a proper subsequence of local sequence
678            */
679           String msg = sequence.getName() + " has " + absStart
680                   + " prefixed residues compared to "
681                   + retrievedSeq.getName();
682           addWarningMessage(warningMessages, msg);
683
684           /*
685            * So create a mapping to the external entry from the matching region of 
686            * the local sequence, and leave local start/end untouched. 
687            */
688           mp = new Mapping(null,
689                   new int[]
690                   { sequenceStart + absStart,
691                       sequenceStart + absStart + entrySeq.length() - 1 },
692                   new int[]
693                   { retrievedSeq.getStart(),
694                       retrievedSeq.getStart() + entrySeq.length() - 1 },
695                   1, 1);
696           updateRefFrame = false;
697         }
698         else
699         {
700           /*
701            * local sequence is a subsequence of (or matches) retrieved sequence
702            */
703           remoteEnclosesLocal = true;
704           mp = null;
705
706           if (updateRefFrame)
707           {
708             /*
709              * relocate existing sequence features by offset
710              */
711             int startShift = absStart - sequenceStart + 1;
712             if (startShift != 0)
713             {
714               modified |= sequence.getFeatures().shiftFeatures(startShift);
715             }
716           }
717         }
718
719         System.out.println("Adding dbrefs to " + sequence.getName()
720                 + " from " + dbSource + " sequence : "
721                 + retrievedSeq.getName());
722         sequence.transferAnnotation(retrievedSeq, mp);
723
724         absStart += retrievedSeq.getStart();
725         int absEnd = absStart + nonGapped.length() - 1;
726         if (!trimDatasetSeqs)
727         {
728           /*
729            * update start position and/or expand to longer retrieved sequence
730            */
731           if (!retrievedSeqString.equals(sequence.getSequenceAsString())
732                   && remoteEnclosesLocal)
733           {
734             sequence.setSequence(retrievedSeqString);
735             modified = true;
736             addWarningMessage(warningMessages,
737                     "Sequence for " + sequence.getName() + " expanded from "
738                             + retrievedSeq.getName());
739           }
740           if (sequence.getStart() != retrievedSeq.getStart())
741           {
742             sequence.setStart(retrievedSeq.getStart());
743             modified = true;
744             if (absStart != sequenceStart)
745             {
746               addWarningMessage(warningMessages,
747                       "Start/end position for " + sequence.getName()
748                               + " updated from " + retrievedSeq.getName());
749             }
750           }
751         }
752         if (updateRefFrame)
753         {
754           // finally, update local sequence reference frame if we're allowed
755           if (trimDatasetSeqs)
756           {
757             // just fix start/end
758             if (sequence.getStart() != absStart
759                     || sequence.getEnd() != absEnd)
760             {
761               sequence.setStart(absStart);
762               sequence.setEnd(absEnd);
763               modified = true;
764               addWarningMessage(warningMessages,
765                       "Start/end for " + sequence.getName()
766                               + " updated from " + retrievedSeq.getName());
767             }
768           }
769           // search for alignment sequences to update coordinate frame for
770           for (int alsq = 0; alsq < alseqs.length; alsq++)
771           {
772             if (alseqs[alsq].getDatasetSequence() == sequence)
773             {
774               String ngAlsq = AlignSeq
775                       .extractGaps("-. ",
776                               alseqs[alsq].getSequenceAsString())
777                       .toUpperCase();
778               int oldstrt = alseqs[alsq].getStart();
779               alseqs[alsq].setStart(sequence.getSequenceAsString()
780                       .toUpperCase().indexOf(ngAlsq) + sequence.getStart());
781               if (oldstrt != alseqs[alsq].getStart())
782               {
783                 alseqs[alsq].setEnd(
784                         ngAlsq.length() + alseqs[alsq].getStart() - 1);
785                 modified = true;
786               }
787             }
788           }
789           // TODO: search for all other references to this dataset sequence, and
790           // update start/end
791           // TODO: update all AlCodonMappings which involve this alignment
792           // sequence (e.g. Q30167 cdna translation from exon2 product (vamsas
793           // demo)
794         }
795         // and remove it from the rest
796         // TODO: decide if we should remove annotated sequence from set
797         sdataset.remove(sequence);
798         // TODO: should we make a note of sequences that have received new DB
799         // ids, so we can query all enabled DAS servers for them ?
800       }
801     }
802     return modified;
803   }
804
805   /**
806    * Adds the message to the list unless it already contains it
807    * 
808    * @param messageList
809    * @param msg
810    */
811   void addWarningMessage(List<String> messageList, String msg)
812   {
813     if (!messageList.contains(msg))
814     {
815       messageList.add(msg);
816     }
817   }
818
819   /**
820    * loop thru and collect additional sequences in Map.
821    * 
822    * @param sequencesArray
823    * @return
824    */
825   private SequenceI[] recoverDbSequences(SequenceI[] sequencesArray)
826   {
827     Vector<SequenceI> nseq = new Vector<>();
828     for (int i = 0; sequencesArray != null
829             && i < sequencesArray.length; i++)
830     {
831       nseq.addElement(sequencesArray[i]);
832       DBRefEntry[] dbr = sequencesArray[i].getDBRefs();
833       Mapping map = null;
834       for (int r = 0; (dbr != null) && r < dbr.length; r++)
835       {
836         if ((map = dbr[r].getMap()) != null)
837         {
838           if (map.getTo() != null && !nseq.contains(map.getTo()))
839           {
840             nseq.addElement(map.getTo());
841           }
842         }
843       }
844     }
845     if (nseq.size() > 0)
846     {
847       sequencesArray = new SequenceI[nseq.size()];
848       nseq.toArray(sequencesArray);
849     }
850     return sequencesArray;
851   }
852 }