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