minor bug fixes and temporary alignment title setting to vamsas object id. this versi...
[jalview.git] / src / jalview / io / VamsasDatastore.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19
20 package jalview.io;
21
22 import org.vamsas.client.Vobject;
23 import org.vamsas.client.VorbaId;
24 import org.vamsas.objects.core.*;
25 import org.vamsas.objects.utils.DocumentStuff;
26 import org.vamsas.test.simpleclient.ClientDoc;
27
28 import jalview.bin.Cache;
29 import jalview.datamodel.AlignmentAnnotation;
30 import jalview.datamodel.AlignmentI;
31 import jalview.datamodel.AlignmentView;
32 import jalview.datamodel.DBRefEntry;
33 import jalview.datamodel.SequenceFeature;
34 import jalview.datamodel.SequenceI;
35 import jalview.gui.*;
36
37 import java.io.*;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.Hashtable;
41 import java.util.IdentityHashMap;
42 import java.util.Vector;
43 import java.util.jar.*;
44 import org.exolab.castor.xml.*;
45 import org.exolab.castor.mapping.Mapping;
46
47 /*
48  * 
49  * static {
50  * org.exolab.castor.util.LocalConfiguration.getInstance().getProperties().setProperty(
51  * "org.exolab.castor.serializer", "org.apache.xml.serialize.XMLSerilazizer"); }
52  * 
53  */
54
55 public class VamsasDatastore {
56   Entry provEntry = null;
57
58   // AlignViewport av;
59
60   org.exolab.castor.types.Date date = new org.exolab.castor.types.Date(
61       new java.util.Date());
62
63   ClientDoc cdoc;
64
65   Hashtable vobj2jv;
66
67   IdentityHashMap jv2vobj;
68
69   public VamsasDatastore(ClientDoc cdoc, Hashtable vobj2jv,
70       IdentityHashMap jv2vobj, Entry provEntry) {
71       this.cdoc = cdoc;
72     this.vobj2jv = vobj2jv;
73     this.jv2vobj = jv2vobj;
74     this.provEntry = provEntry;
75   }
76
77   /*
78    * public void storeJalview(String file, AlignFrame af) { try { // 1. Load the
79    * mapping information from the file Mapping map = new
80    * Mapping(getClass().getClassLoader()); java.net.URL url =
81    * getClass().getResource("/jalview_mapping.xml"); map.loadMapping(url); // 2.
82    * Unmarshal the data // Unmarshaller unmar = new Unmarshaller();
83    * //unmar.setIgnoreExtraElements(true); //unmar.setMapping(map); // uni =
84    * (UniprotFile) unmar.unmarshal(new FileReader(file)); // 3. marshal the data
85    * with the total price back and print the XML in the console Marshaller
86    * marshaller = new Marshaller( new FileWriter(file) );
87    * 
88    * marshaller.setMapping(map); marshaller.marshal(af); } catch (Exception e) {
89    * e.printStackTrace(); } }
90    * 
91    * 
92    */
93   /**
94    * @return the Vobject bound to Jalview datamodel object
95    */
96   protected Vobject getjv2vObj(Object jvobj) {
97     if (jv2vobj.containsKey(jvobj))
98       return cdoc.getObject((VorbaId) jv2vobj.get(jvobj));
99     return null;
100   }
101
102   /**
103    * 
104    * @param vobj
105    * @return Jalview datamodel object bound to the vamsas document object
106    */
107   protected Object getvObj2jv(org.vamsas.client.Vobject vobj) {
108     VorbaId id = vobj.getVorbaId();
109     if (id == null)
110     {
111       id = cdoc.registerObject(vobj);
112       Cache.log
113       .debug("Registering new object and returning null for getvObj2jv");
114       return null;
115     }
116     if (vobj2jv.containsKey(vobj.getVorbaId()))
117       return vobj2jv.get(vobj.getVorbaId());
118     return null;
119   }
120
121   protected void bindjvvobj(Object jvobj, org.vamsas.client.Vobject vobj) {
122     VorbaId id = vobj.getVorbaId();
123     if (id == null)
124     {
125       id = cdoc.registerObject(vobj);
126       if (id==null || vobj.getVorbaId()==null)
127         Cache.log.error("Failed to get id for "+(vobj.isRegisterable() ? "registerable" : "unregisterable") +" object "+vobj);
128     }
129     
130     if (vobj2jv.containsKey(vobj.getVorbaId()) && !((VorbaId)vobj2jv.get(vobj.getVorbaId())).equals(jvobj)) {
131       Cache.log.debug("Warning? Overwriting existing vamsas id binding for "+vobj.getVorbaId(), new Exception("Overwriting vamsas id binding."));
132     }
133     else if (jv2vobj.containsKey(jvobj) && !((VorbaId)jv2vobj.get(jvobj)).equals(vobj.getVorbaId())) 
134     {
135       Cache.log.debug("Warning? Overwriting existing jalview object binding for "+jvobj, new Exception("Overwriting jalview object binding."));
136     }
137     /* Cache.log.error("Attempt to make conflicting object binding! "+vobj+" id " +vobj.getVorbaId()+" already bound to "+getvObj2jv(vobj)+" and "+jvobj+" already bound to "+getjv2vObj(jvobj),new Exception("Excessive call to bindjvvobj"));
138     }*/
139     // we just update the hash's regardless!
140     vobj2jv.put(vobj.getVorbaId(), jvobj);
141     // JBPNote - better implementing a hybrid invertible hash.
142     jv2vobj.put(jvobj, vobj.getVorbaId());   
143   }
144
145   /**
146    * put the alignment viewed by AlignViewport into cdoc.
147    * 
148    * @param av
149    */
150   public void storeVAMSAS(AlignViewport av) {
151     try
152     {
153       jalview.datamodel.AlignmentI jal = av.getAlignment();
154       boolean nw = false;
155       VAMSAS root = null; // will be resolved based on Dataset Parent.
156       // /////////////////////////////////////////
157       // SAVE THE DATASET
158       if (jal.getDataset() == null)
159       {
160         Cache.log.warn("Creating new dataset for an alignment.");
161         jal.setDataset(null);
162       }
163       DataSet dataset = (DataSet) getjv2vObj(jal.getDataset());
164       if (dataset == null)
165       {
166         root = cdoc.getVamsasRoots()[0]; // default vamsas root for modifying.
167         dataset = new DataSet();
168         root.addDataSet(dataset);
169         bindjvvobj(jal.getDataset(), dataset);
170         dataset.setProvenance(dummyProvenance());
171         dataset.getProvenance().addEntry(provEntry);
172         nw = true;
173       }
174       else
175       {
176         root = (VAMSAS) dataset.getV_parent();
177       }
178       // update dataset
179       Sequence sequence;
180       DbRef dbref;
181       // set new dataset and alignment sequences based on alignment Nucleotide
182       // flag.
183       // this *will* break when alignment contains both nucleotide and amino
184       // acid sequences.
185       String dict = jal.isNucleotide() ? org.vamsas.objects.utils.SymbolDictionary.STANDARD_NA
186           : org.vamsas.objects.utils.SymbolDictionary.STANDARD_AA;
187       for (int i = 0; i < jal.getHeight(); i++)
188       {
189         SequenceI sq = jal.getSequenceAt(i).getDatasetSequence(); // only insert
190         // referenced
191         // sequences
192         // to dataset.
193         sequence = (Sequence) getjv2vObj(sq);
194         if (sequence == null)
195         {
196           sequence = new Sequence();
197           bindjvvobj(sq, sequence);
198           sq.setVamsasId(sequence.getVorbaId().getId());
199           sequence.setSequence(sq.getSequence());
200           sequence.setDictionary(dict);
201           sequence.setName(jal.getDataset().getSequenceAt(i).getName());
202           sequence.setStart(jal.getDataset().getSequenceAt(i).getStart());
203           sequence.setEnd(jal.getDataset().getSequenceAt(i).getEnd());
204           dataset.addSequence(sequence);
205         }
206         else
207         {
208           // verify principal attributes. and update any new
209           // features/references.
210           System.out.println("update dataset sequence object.");
211         }
212         if (sq.getSequenceFeatures() != null)
213         {
214           int sfSize = sq.getSequenceFeatures().length;
215
216           for (int sf = 0; sf < sfSize; sf++)
217           {
218             jalview.datamodel.SequenceFeature feature = (jalview.datamodel.SequenceFeature) sq
219             .getSequenceFeatures()[sf];
220
221             DataSetAnnotations dsa = (DataSetAnnotations) getjv2vObj(feature);
222             if (dsa == null)
223             {
224               dsa = (DataSetAnnotations) getDSAnnotationFromJalview(
225                   new DataSetAnnotations(), feature);
226               if (dsa.getProvenance() == null)
227               {
228                 dsa.setProvenance(new Provenance());
229               }
230               addProvenance(dsa.getProvenance(), "created"); // JBPNote - need
231               // to update
232               dsa.setSeqRef(sequence);
233               bindjvvobj(feature, dsa);
234               dataset.addDataSetAnnotations(dsa);
235             }
236             else
237             {
238               // todo: verify and update dataset annotations for sequence
239               System.out.println("update dataset sequence annotations.");
240             }
241           }
242         }
243
244         if (sq.getDBRef() != null)
245         {
246           DBRefEntry[] entries = sq.getDBRef();
247           jalview.datamodel.DBRefEntry dbentry;
248           for (int db = 0; db < entries.length; db++)
249           {
250             dbentry = entries[db];
251             dbref = (DbRef) getjv2vObj(dbentry);
252             if (dbref == null)
253             {
254               dbref = new DbRef();
255               bindjvvobj(dbentry, dbref);
256               dbref.setAccessionId(dbentry.getAccessionId());
257               dbref.setSource(dbentry.getSource());
258               dbref.setVersion(dbentry.getVersion());
259               /*
260                * TODO: Maps are not yet supported by Jalview. Map vMap = new
261                * Map(); vMap.set dbref.addMap(vMap);
262                */
263               sequence.addDbRef(dbref);
264             }
265             else
266             {
267               // TODO: verify and update dbrefs in vamsas document
268               // there will be trouble when a dataset sequence is modified to
269               // contain more residues than were originally referenced - we must
270               // then make a number of dataset sequence entries
271               System.out
272               .println("update dataset sequence database references.");
273             }
274           }
275
276         }
277       }
278       // dataset.setProvenance(getVamsasProvenance(jal.getDataset().getProvenance()));
279       // ////////////////////////////////////////////
280
281       // ////////////////////////////////////////////
282       // Save the Alignments
283
284       Alignment alignment = (Alignment) getjv2vObj(av); // this is so we can get the alignviewport back 
285       if (alignment == null)
286       {
287         alignment = new Alignment();
288         bindjvvobj(av, alignment);
289         if (alignment.getProvenance() == null)
290           alignment.setProvenance(new Provenance());
291         addProvenance(alignment.getProvenance(), "added"); // TODO: insert some
292         // sensible source
293         // here
294         dataset.addAlignment(alignment);
295         alignment.setGapChar(String.valueOf(av.getGapCharacter()));
296         AlignmentSequence alseq = null;
297         for (int i = 0; i < jal.getHeight(); i++)
298         {
299           alseq = new AlignmentSequence();
300           // TODO: VAMSAS: translate lowercase symbols to annotation ?
301           alseq.setSequence(jal.getSequenceAt(i).getSequence());
302           alseq.setName(jal.getSequenceAt(i).getName());
303           alseq.setStart(jal.getSequenceAt(i).getStart());
304           alseq.setEnd(jal.getSequenceAt(i).getEnd());
305           alseq.setRefid(getjv2vObj(jal.getSequenceAt(i).getDatasetSequence()));
306           alignment.addAlignmentSequence(alseq);
307           bindjvvobj(jal.getSequenceAt(i), alseq);
308         }
309       }
310       else
311       {
312         // todo: verify and update mutable alignment props.
313         if (alignment.getModifiable())
314         {
315           System.out.println("update alignment in document.");
316         }
317         else
318         {
319           System.out
320           .println("update edited alignment to new alignment in document.");
321         }
322       }
323       // ////////////////////////////////////////////
324       // SAVE Alignment Sequence Features
325       for (int i = 0, iSize = alignment.getAlignmentSequenceCount(); i < iSize; i++)
326       {
327         AlignmentSequence valseq;
328         SequenceI alseq = (SequenceI) getvObj2jv(valseq = alignment
329             .getAlignmentSequence(i));
330         if (alseq != null && alseq.getSequenceFeatures() != null)
331         {
332           jalview.datamodel.SequenceFeature[] features = alseq
333           .getSequenceFeatures();
334           for (int f = 0; f < features.length; f++)
335           {
336             if (features[f] != null)
337             {
338               AlignmentSequenceAnnotation valseqf = (AlignmentSequenceAnnotation) getjv2vObj(features[i]);
339               if (valseqf == null)
340               {
341
342                 valseqf = (AlignmentSequenceAnnotation) getDSAnnotationFromJalview(
343                     new AlignmentSequenceAnnotation(), features[i]);
344                 if (valseqf.getProvenance() == null)
345                 {
346                   valseqf.setProvenance(new Provenance());
347                 }
348                 addProvenance(valseqf.getProvenance(), "created"); // JBPNote -
349                 // need to
350                 // update
351                 bindjvvobj(features[i], valseqf);
352                 valseq.addAlignmentSequenceAnnotation(valseqf);
353               }
354             }
355
356           }
357         }
358       }
359
360       // ////////////////////////////////////////////
361       // SAVE ANNOTATIONS
362       if (jal.getAlignmentAnnotation() != null)
363       {
364         jalview.datamodel.AlignmentAnnotation[] aa = jal
365         .getAlignmentAnnotation();
366         java.util.HashMap AlSeqMaps = new HashMap(); // stores int maps from
367         // alignment columns to
368         // sequence positions.
369         for (int i = 0; i < aa.length; i++)
370         {
371           if (aa[i] == null || isJalviewOnly(aa[i]))
372           {
373             continue;
374           }
375           if (aa[i].sequenceRef != null)
376           {
377             org.vamsas.objects.core.AlignmentSequence alsref = (org.vamsas.objects.core.AlignmentSequence) getjv2vObj(aa[i].sequenceRef);
378             org.vamsas.objects.core.AlignmentSequenceAnnotation an = (org.vamsas.objects.core.AlignmentSequenceAnnotation) getjv2vObj(aa[i]);
379             int[] gapMap = null;
380             if (AlSeqMaps.containsKey(aa[i].sequenceRef))
381             {
382               gapMap = (int[]) AlSeqMaps.get(aa[i].sequenceRef);
383             }
384             else
385             {
386               gapMap = new int[aa[i].sequenceRef.getLength()];
387               // map from alignment position to sequence position.
388               int[] sgapMap = aa[i].sequenceRef.gapMap();
389               for (int a = 0; a < sgapMap.length; a++)
390                 gapMap[sgapMap[a]] = a;
391             }
392             if (an == null)
393             {
394               an = new org.vamsas.objects.core.AlignmentSequenceAnnotation();
395               Seg vSeg = new Seg();
396               vSeg.setStart(1);
397               vSeg.setInclusive(true);
398               vSeg.setEnd(gapMap.length);
399               an.addSeg(vSeg);
400               an.setType("jalview:SecondaryStructurePrediction");// TODO: better fix this rough guess ;)
401               alsref.addAlignmentSequenceAnnotation(an);
402               bindjvvobj(aa[i],an);
403               // LATER: much of this is verbatim from the alignmentAnnotation
404               // method below. suggests refactoring to make rangeAnnotation the
405               // base class
406               an.setDescription(aa[i].description);
407               if (aa[i].graph > 0)
408                 an.setGraph(true); // aa[i].graph);
409               else
410                 an.setGraph(false);
411               an.setLabel(aa[i].label);
412               an.setProvenance(dummyProvenance()); // get provenance as user
413               // created, or jnet, or
414               // something else.
415               an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote -
416               // originally we
417               // were going to
418               // store
419               // graphGroup in
420               // the Jalview
421               // specific
422               // bits.
423               AnnotationElement ae;
424               for (int a = 0; a < aa[i].annotations.length; a++)
425               {
426                 if (aa[i].annotations[a] == null)
427                 {
428                   continue;
429                 }
430
431                 ae = new AnnotationElement();
432                 ae.setDescription(aa[i].annotations[a].description);
433                 ae.addGlyph(new Glyph());
434                 ae.getGlyph(0)
435                 .setContent(aa[i].annotations[a].displayCharacter); // assume
436                 // jax-b
437                 // takes
438                 // care
439                 // of
440                 // utf8
441                 // translation
442                 ae.addValue(aa[i].annotations[a].value);
443                 ae.setPosition(gapMap[a]+1); // position w.r.t. AlignmentSequence
444                 // symbols
445                 if (aa[i].annotations[a].secondaryStructure != ' ')
446                 {
447                   // we only write an annotation where it really exists.
448                   Glyph ss = new Glyph();
449                   ss
450                   .setDict(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
451                   ss.setContent(String
452                       .valueOf(aa[i].annotations[a].secondaryStructure));
453                   ae.addGlyph(ss);
454                 }
455                 an.addAnnotationElement(ae);
456               }
457             }
458             else
459             {
460               // update reference sequence Annotation
461               if (an.getModifiable())
462               {
463                 // verify existing alignment sequence annotation is up to date
464                 System.out.println("update alignment sequence annotation.");
465               }
466               else
467               {
468                 // verify existing alignment sequence annotation is up to date
469                 System.out
470                 .println("make new alignment sequence annotation if modification has happened.");
471               }
472             }
473           }
474           else
475           {
476             // add Alignment Annotation
477             org.vamsas.objects.core.AlignmentAnnotation an = (org.vamsas.objects.core.AlignmentAnnotation) getjv2vObj(aa[i]);
478             if (an == null)
479             {
480               an = new org.vamsas.objects.core.AlignmentAnnotation();
481               an.setType("jalview:AnnotationRow");
482               an.setDescription(aa[i].description);
483               alignment.addAlignmentAnnotation(an);
484               Seg vSeg = new Seg();
485               vSeg.setStart(1);
486               vSeg.setInclusive(true);
487               vSeg.setEnd(jal.getWidth());
488               an.addSeg(vSeg);
489               if (aa[i].graph > 0)
490                 an.setGraph(true); // aa[i].graph);
491               an.setLabel(aa[i].label);
492               an.setProvenance(dummyProvenance());
493               if (aa[i].graph!=aa[i].NO_GRAPH) {
494                 an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote -
495                 // originally we
496               // were going to
497               // store
498               // graphGroup in
499               // the Jalview
500               // specific
501               // bits.
502                 an.setGraph(true);
503               } else {
504                 an.setGraph(false);
505               }
506               AnnotationElement ae;
507
508               for (int a = 0; a < aa[i].annotations.length; a++)
509               {
510                 if ((aa[i] == null) || (aa[i].annotations[a] == null))
511                 {
512                   continue;
513                 }
514
515                 ae = new AnnotationElement();
516                 ae.setDescription(aa[i].annotations[a].description);
517                 ae.addGlyph(new Glyph());
518                 ae.getGlyph(0)
519                 .setContent(aa[i].annotations[a].displayCharacter); // assume
520                 // jax-b
521                 // takes
522                 // care
523                 // of
524                 // utf8
525                 // translation
526                 ae.addValue(aa[i].annotations[a].value);
527                 ae.setPosition(a+1);
528                 if (aa[i].annotations[a].secondaryStructure != ' ')
529                 {
530                   Glyph ss = new Glyph();
531                   ss
532                   .setDict(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
533                   ss.setContent(String
534                       .valueOf(aa[i].annotations[a].secondaryStructure));
535                   ae.addGlyph(ss);
536                 }
537                 an.addAnnotationElement(ae);
538               }
539               if (aa[i].editable) {
540                 //an.addProperty(newProperty("jalview:editable", null, "true"));
541                 an.setModifiable(true);
542               }
543               if (aa[i].graph!=jalview.datamodel.AlignmentAnnotation.NO_GRAPH) {
544                 an.setGraph(true);
545                 an.setGroup(Integer.toString(aa[i].graphGroup));
546                 an.addProperty(newProperty("jalview:graphType",null,
547                     ((aa[i].graph==jalview.datamodel.AlignmentAnnotation.BAR_GRAPH) ? "BAR_GRAPH" : "LINE_GRAPH")));
548
549                 /** and on and on.. 
550                  vProperty=new Property();
551                   vProperty.setName("jalview:graphThreshhold");
552                   vProperty.setContent(aa[i].threshold);
553                  */
554
555               }
556             }
557             else
558             {
559               if (an.getModifiable())
560               {
561                 // verify annotation - update (perhaps)
562                 Cache.log.info("update alignment sequence annotation. not yet implemented.");
563               }
564               else
565               {
566                 // verify annotation - update (perhaps)
567                 Cache.log.info("updated alignment sequence annotation added.");
568               }
569             }
570           }
571         }
572       }
573       // /////////////////////////////////////////////////////
574
575       // //////////////////////////////////////////////
576       // /SAVE THE TREES
577       // /////////////////////////////////
578       // FIND ANY ASSOCIATED TREES
579       if (Desktop.desktop != null)
580       {
581         javax.swing.JInternalFrame[] frames = Desktop.desktop.getAllFrames();
582
583         for (int t = 0; t < frames.length; t++)
584         {
585           if (frames[t] instanceof TreePanel)
586           {
587             TreePanel tp = (TreePanel) frames[t];
588
589             if (tp.getAlignment() == jal)
590             {
591               Tree tree = (Tree) getjv2vObj(tp);
592               if (tree == null)
593               {
594                 tree = new Tree();
595                 bindjvvobj(tp, tree);
596                 tree.setTitle(tp.getTitle());
597                 Newick newick = new Newick();
598                 // TODO: translate sequenceI to leaf mappings to vamsas
599                 // references - see tree specification in schema.
600                 newick.setContent(tp.getTree().toString());
601                 newick.setTitle(tp.getTitle());
602                 tree.addNewick(newick);
603                 tree.setProvenance(makeTreeProvenance(jal, tp));
604                 alignment.addTree(tree);
605               }
606               else
607               {
608                 if (tree.getModifiable())
609                 {
610                   // verify any changes.
611                   System.out.println("Update tree in document.");
612                 }
613                 else
614                 {
615                   System.out
616                   .println("Add modified tree as new tree in document.");
617                 }
618               }
619             }
620           }
621         }
622       }
623       // Store Jalview specific stuff in the Jalview appData
624       // not implemented in the SimpleDoc interface.
625     }
626
627     catch (Exception ex)
628     {
629       ex.printStackTrace();
630     }
631
632   }
633
634   private Property newProperty(String name, String type, String content) {
635     Property vProperty=new Property();
636     vProperty.setName(name);
637     if (type!=null)
638       vProperty.setType(type);
639     else
640       vProperty.setType("String");
641     vProperty.setContent(content);
642     return vProperty;
643   }
644
645   /**
646    * correctly create a RangeAnnotation from a jalview sequence feature
647    * 
648    * @param dsa
649    *          (typically DataSetAnnotations or AlignmentSequenceAnnotation)
650    * @param feature
651    *          (the feature to be mapped from)
652    * @return
653    */
654   private RangeAnnotation getDSAnnotationFromJalview(RangeAnnotation dsa,
655       SequenceFeature feature) {
656     dsa.setType(feature.getType());
657     Seg vSeg = new Seg();
658     vSeg.setStart(feature.getBegin());
659     vSeg.setEnd(feature.getEnd());
660     vSeg.setInclusive(true);
661     dsa.addSeg(vSeg);
662     dsa.setDescription(feature.getDescription());
663     dsa.setStatus(feature.getStatus());
664     if (feature.links != null && feature.links.size() > 0)
665     {
666       for (int i = 0, iSize = feature.links.size(); i < iSize; i++)
667       {
668         String link = (String) feature.links.elementAt(i);
669         int sep = link.indexOf('|');
670         if (sep > -1)
671         {
672           Link vLink = new Link();
673           if (sep > 0)
674             vLink.setContent(link.substring(0, sep - 1));
675           else
676             vLink.setContent("");
677           vLink.setHref(link.substring(sep + 1)); // TODO: validate href.
678           dsa.addLink(vLink);
679         }
680       }
681     }
682     dsa.setGroup(feature.getFeatureGroup());
683     return dsa;
684   }
685
686   /**
687    * correctly creates provenance for trees calculated on an alignment by
688    * jalview.
689    * 
690    * @param jal
691    * @param tp
692    * @return
693    */
694   private Provenance makeTreeProvenance(AlignmentI jal, TreePanel tp) {
695     Provenance prov = new Provenance();
696     prov.addEntry(new Entry());
697     prov.getEntry(0).setAction("imported "+tp.getTitle());
698     prov.getEntry(0).setUser(provEntry.getUser());
699     prov.getEntry(0).setApp(provEntry.getApp());
700     prov.getEntry(0).setDate(provEntry.getDate());
701     if (tp.getTree().hasOriginalSequenceData())
702     {
703       Input vInput = new Input();
704       // LATER: check to see if tree input data is contained in this alignment -
705       // or just correctly resolve the tree's seqData to the correct alignment in
706       // the document.
707       vInput.setObjRef(getjv2vObj(jal));
708       prov.getEntry(0).setAction("created "+tp.getTitle());
709       prov.getEntry(0).addInput(vInput);
710       vInput.setName("jalview:seqdist");
711       prov.getEntry(0).addParam(new Param());
712       prov.getEntry(0).getParam(0).setName("treeType");
713       prov.getEntry(0).getParam(0).setType("utf8");
714       prov.getEntry(0).getParam(0).setContent("NJ");
715       
716       int ranges[] = tp.getTree().seqData.getVisibleContigs();
717       for (int r = 0; r < ranges.length; r += 2)
718       {
719         Seg visSeg = new Seg();
720         visSeg.setStart(ranges[r]);
721         visSeg.setEnd(ranges[r + 1]);
722         visSeg.setInclusive(true);
723         vInput.addSeg(visSeg);
724       }
725     }
726     return prov;
727   }
728
729   /**
730    * 
731    * @param tp
732    * @return Object[] { AlignmentView, AlignmentI - reference alignment for
733    *         input }
734    */
735   private Object[] recoverInputData(Provenance tp) {
736     for (int pe = 0; pe < tp.getEntryCount(); pe++)
737     {
738       if (tp.getEntry(pe).getInputCount() > 0)
739       {
740         if (tp.getEntry(pe).getInputCount() > 1)
741           Cache.log.warn("Ignoring additional input spec in provenance entry "
742               + tp.getEntry(pe).toString());
743         // LATER: deal sensibly with multiple inputs.
744         Input vInput = tp.getEntry(pe).getInput(0);
745         if (vInput.getObjRef() instanceof org.vamsas.objects.core.Alignment)
746         {
747           // recover an AlignmentView for the input data
748           AlignmentI jal = (AlignmentI) getvObj2jv((org.vamsas.client.Vobject) vInput
749               .getObjRef());
750           jalview.datamodel.CigarArray view = jal.getCompactAlignment();
751           int from = 0, to = jal.getWidth();
752           for (int r = 0, s = vInput.getSegCount(); r < s; r++)
753           {
754             Seg visSeg = vInput.getSeg(r);
755             int se[] = getSegRange(visSeg,true); // jalview doesn't do bidirection alignments yet.
756             if (to > se[1])
757               Cache.log.warn("Ignoring invalid segment in InputData spec.");
758             else
759             {
760               if (se[0] > from)
761               {
762                 view.deleteRange(from, se[0] - 1);
763               }
764               from = se[1] + 1;
765             }
766           }
767           if (from < to)
768           {
769             view.deleteRange(from, to); // final deletion - TODO: check off by
770             // one for to
771           }
772           return new Object[] { new AlignmentView(view), jal };
773         }
774       }
775     }
776     Cache.log.debug("Returning null for input data recovery from provenance.");
777     return null;
778   }
779
780   /**
781    * get start<end range of segment, adjusting for inclusivity flag and
782    * polarity.
783    *  
784    * @param visSeg
785    * @param ensureDirection when true - always ensure start is less than end.
786    * @return int[] { start, end, direction} where direction==1 for range running from end to start.
787    */
788   private int[] getSegRange(Seg visSeg, boolean ensureDirection) {
789     boolean incl = visSeg.getInclusive();
790     // adjust for inclusive flag.
791     int pol = (visSeg.getStart() <= visSeg.getEnd()) ? 1 : -1; // polarity of
792     // region.
793     int start = visSeg.getStart() + (incl ? 0 : pol);
794     int end = visSeg.getEnd() + (incl ? 0 : -pol);
795     if (ensureDirection && pol==-1)
796     {
797       // jalview doesn't deal with inverted ranges, yet.
798       int t = end;
799       end = start;
800       start = t;
801     }
802     return new int[] { start, end, pol<0 ? 1 : 0 };
803   }
804
805   /**
806    * 
807    * @param annotation
808    * @return true if annotation is not to be stored in document
809    */
810   private boolean isJalviewOnly(AlignmentAnnotation annotation) {
811     return annotation.label.equals("Quality")
812     || annotation.label.equals("Conservation")
813     || annotation.label.equals("Consensus");
814   }
815   /**
816    * This will return the first AlignFrame viewing AlignViewport av.
817    * It will break if there are more than one AlignFrames viewing a particular av.
818    * This also shouldn't be in the io package.
819    * @param av
820    * @return alignFrame for av
821    */
822   public AlignFrame getAlignFrameFor(AlignViewport av) {
823     if (Desktop.desktop != null)
824     {
825       javax.swing.JInternalFrame[] frames = Desktop.desktop.getAllFrames();
826
827       for (int t = 0; t < frames.length; t++)
828       {
829         if (frames[t] instanceof AlignFrame) {
830           if (((AlignFrame) frames[t]).getViewport()==av)
831             return (AlignFrame) frames[t];
832         }
833       }
834     }
835     return null;
836   }
837   public void updateToJalview() {
838     VAMSAS _roots[] = cdoc.getVamsasRoots();
839
840     for (int _root = 0; _root<_roots.length; _root++) {
841       VAMSAS root = _roots[_root];
842       boolean newds=false;
843       for (int _ds=0,_nds=root.getDataSetCount(); _ds<_nds; _ds++) {
844         // ///////////////////////////////////
845         // ///LOAD DATASET
846         DataSet dataset = root.getDataSet(_ds);
847         int i, iSize = dataset.getSequenceCount();
848         Vector dsseqs;
849         jalview.datamodel.Alignment jdataset = (jalview.datamodel.Alignment) getvObj2jv(dataset);
850         int jremain=0;
851         if (jdataset==null) {
852           Cache.log.debug("Initialising new jalview dataset fields");
853           newds=true;
854           dsseqs=new Vector();
855         } else {
856           Cache.log.debug("Update jalview dataset from vamsas.");
857           jremain=jdataset.getHeight();
858           dsseqs=jdataset.getSequences();
859         }
860
861         // TODO: test sequence merging - we preserve existing non vamsas
862         // sequences but add in any new vamsas ones, and don't yet update any
863         // sequence attributes
864         for (i = 0; i < iSize ; i++)
865         {
866           Sequence vdseq = dataset.getSequence(i);
867           jalview.datamodel.SequenceI dsseq = (SequenceI) getvObj2jv(vdseq);
868           if (dsseq!=null) {
869             if (!dsseq.getSequence().equals(vdseq.getSequence()))
870               throw new Error("Broken! - mismatch of dataset sequence and jalview internal dataset sequence.");
871             jremain--;
872           } else {
873             dsseq = new jalview.datamodel.Sequence(
874                 dataset.getSequence(i).getName(),
875                 dataset.getSequence(i).getSequence(),
876                 dataset.getSequence(i).getStart(),
877                 dataset.getSequence(i).getEnd()  );
878             bindjvvobj(dsseq, dataset.getSequence(i));
879             dsseq.setVamsasId(dataset.getSequence(i).getVorbaId().getId());
880             dsseqs.add(dsseq);
881           }
882           if (vdseq.getDbRefCount()>0) {
883             DbRef [] dbref = vdseq.getDbRef();
884             for(int db=0; db<dbref.length; db++)
885             {
886               jalview.datamodel.DBRefEntry dbr=(jalview.datamodel.DBRefEntry) getvObj2jv(dbref[db]);
887               if (dbr==null) {
888                 // add new dbref
889                 dsseq.addDBRef(dbr= new jalview.datamodel.DBRefEntry
890                     (
891                         dbref[db].getSource().toString(),
892                         dbref[db].getVersion().toString(),
893                         dbref[db].getAccessionId().toString()));
894                 bindjvvobj(dbr, dbref[db]);
895               }
896             }
897           }
898         }
899
900         if (newds) {
901           SequenceI[] seqs = new SequenceI[dsseqs.size()];
902           for (i=0,iSize=dsseqs.size(); i<iSize; i++) {
903             seqs[i]=(SequenceI) dsseqs.elementAt(i);
904             dsseqs.setElementAt(null, i);
905           }
906           jdataset = new jalview.datamodel.Alignment(seqs);
907           Cache.log.debug("New vamsas dataset imported into jalview.");
908           bindjvvobj(jdataset, dataset);
909         }
910         // ////////
911         // add any new dataset sequence feature annotations
912         if (dataset.getDataSetAnnotations() != null) {
913           for (int dsa = 0; dsa < dataset.getDataSetAnnotationsCount(); dsa++) {
914             DataSetAnnotations dseta=dataset.getDataSetAnnotations(dsa);
915             SequenceI dsSeq=(SequenceI) getvObj2jv((Vobject) dseta.getSeqRef());
916             if (dsSeq==null) {
917               jalview.bin.Cache.log.warn("Couldn't resolve jalview sequenceI for dataset object reference "+((Vobject)dataset.getDataSetAnnotations(dsa).getSeqRef()).getVorbaId().getId());
918             } else {
919               if (dseta.getAnnotationElementCount()==0) {
920                 jalview.datamodel.SequenceFeature sf=(jalview.datamodel.SequenceFeature) getvObj2jv(dseta);
921                 if (sf==null) {
922                   dsSeq.addSequenceFeature(sf=getJalviewSeqFeature(dseta));
923                   bindjvvobj(sf, dseta);
924                 }
925               } else {
926                 // TODO: deal with alignmentAnnotation style annotation
927                 // appearing on dataset sequences.
928                 // JBPNote: we could just add them to all alignments but
929                 // that may complicate cross references in the jalview
930                 // datamodel
931                 Cache.log.warn("Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
932               }
933             }
934           }
935         }
936
937         if (dataset.getAlignmentCount()>0) {
938           // LOAD ALIGNMENTS from DATASET 
939
940           for (int al=0,nal=dataset.getAlignmentCount(); al<nal; al++) {
941             org.vamsas.objects.core.Alignment alignment = dataset.getAlignment(al);
942             AlignViewport av = (AlignViewport) getvObj2jv(alignment);
943             jalview.datamodel.AlignmentI jal=null;
944             if (av!=null)
945               jal = av.getAlignment(); 
946             iSize = alignment.getAlignmentSequenceCount();
947             boolean newal=(jal==null) ? true : false;
948             Vector newasAnnots=new Vector();
949             char gapChar=' '; // default for new alignments read in from the document
950             if (jal!=null) {
951               dsseqs=jal.getSequences(); // for merge/update
952               gapChar=jal.getGapCharacter();
953             } else {
954               dsseqs=new Vector();
955             }
956             char valGapchar=alignment.getGapChar().charAt(0);
957             for (i = 0; i < iSize; i++)
958             {
959               AlignmentSequence valseq = alignment.getAlignmentSequence(i);
960               jalview.datamodel.SequenceI alseq = (SequenceI) getvObj2jv(valseq);
961               if (alseq!=null) {
962                 //TODO: upperCase/LowerCase situation here ? do we allow it ?
963                 //if (!alseq.getSequence().equals(valseq.getSequence())) {
964                 // throw new Error("Broken! - mismatch of dataset sequence and jalview internal dataset sequence.");
965                 if (Cache.log.isDebugEnabled())
966                   Cache.log.debug("Updating apparently edited sequence "+alseq.getName());
967                 // this might go *horribly* wrong
968                 alseq.setSequence(new String(valseq.getSequence()).replace(valGapchar, gapChar));
969                 jremain--;
970               } else {
971                 alseq = new jalview.datamodel.Sequence(
972                     valseq.getName(),
973                     valseq.getSequence().replace(valGapchar, gapChar),
974                     valseq.getStart(),
975                     valseq.getEnd()  );
976                 
977                 Vobject datsetseq = (Vobject)valseq.getRefid();
978                 if (datsetseq!=null) {
979                   alseq.setDatasetSequence((SequenceI)getvObj2jv(datsetseq)); // exceptions if AlignemntSequence reference isn't a simple SequenceI
980                 } else {
981                   Cache.log.error("Invalid dataset sequence id (null) for alignment sequence "+valseq.getVorbaId());
982                 }
983                 bindjvvobj(alseq, valseq);
984                 alseq.setVamsasId(valseq.getVorbaId().getId());
985                 dsseqs.add(alseq);
986               }
987               if (valseq.getAlignmentSequenceAnnotationCount()>0) {
988                 AlignmentSequenceAnnotation[] vasannot=valseq.getAlignmentSequenceAnnotation();
989                 for (int a=0; a<vasannot.length; a++) {
990                   jalview.datamodel.AlignmentAnnotation asa = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(vasannot[a]); // TODO: 1:many jalview alignment sequence annotations
991                   if (asa==null) {
992                     int se[] = getBounds(vasannot[a]);
993                     asa = getjAlignmentAnnotation(jal, vasannot[a]);
994                     asa.sequenceRef=alseq;
995                     asa.createSequenceMapping(alseq, alseq.getStart()+se[0], false); // TODO: verify that positions in alseqAnnotation correspond to ungapped residue positions.
996                     bindjvvobj(asa, vasannot[a]);
997                     newasAnnots.add(asa);
998                   } else {
999                     // update existing annotation - can do this in place
1000                     if (vasannot[a].getModifiable()) {
1001                       Cache.log.info("UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");
1002                       // TODO: should at least replace with new one - otherwise things will break
1003                       // basically do this:
1004                       // int se[] = getBounds(vasannot[a]);
1005                       // asa.update(getjAlignmentAnnotation(jal, vasannot[a])); //  update from another annotation object in place.
1006                       // asa.createSequenceMapping(alseq, se[0], false); 
1007
1008                     }
1009                   }
1010                 }
1011               }
1012             }
1013             if (jal==null) {
1014               SequenceI[] seqs = new SequenceI[dsseqs.size()];
1015               for (i=0,iSize=dsseqs.size(); i<iSize; i++) {
1016                 seqs[i]=(SequenceI) dsseqs.elementAt(i);
1017                 dsseqs.setElementAt(null, i);
1018               }
1019               jal = new jalview.datamodel.Alignment(seqs);
1020               Cache.log.debug("New vamsas alignment imported into jalview "+alignment.getVorbaId().getId());
1021               jal.setDataset(jdataset);
1022             }
1023             if (newasAnnots!=null && newasAnnots.size()>0) {
1024               // Add the new sequence annotations in to the alignment.
1025               for (int an=0,anSize=newasAnnots.size(); an<anSize; an++) {
1026                 jal.addAnnotation((AlignmentAnnotation) newasAnnots.elementAt(an));
1027                 // TODO: check if anything has to be done - like calling adjustForAlignment or something.
1028                 newasAnnots.setElementAt(null, an);
1029               }
1030               newasAnnots=null;
1031             }
1032             // //////////////////////////////////////////
1033             // //LOAD ANNOTATIONS FOR THE ALIGNMENT
1034             // ////////////////////////////////////
1035             if (alignment.getAlignmentAnnotationCount()>0)
1036             {
1037               org.vamsas.objects.core.AlignmentAnnotation[] an = alignment.getAlignmentAnnotation();
1038
1039               for (int j = 0; j < an.length; j++)
1040               {
1041                 jalview.datamodel.AlignmentAnnotation jan=(jalview.datamodel.AlignmentAnnotation) getvObj2jv(an[j]);
1042                 if (jan!=null) {
1043                   // update or stay the same.
1044                   // TODO: should at least replace with a new one - otherwise things will break
1045                   // basically do this:
1046                   // jan.update(getjAlignmentAnnotation(jal, an[a])); //  update from another annotation object in place.
1047
1048                   Cache.log.debug("update from vamsas alignment annotation to existing jalview alignment annotation.");
1049                   if (an[j].getModifiable()) {
1050                     // TODO: user defined annotation is totally mutable... - so load it up or throw away if locally edited.
1051                     Cache.log.info("NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");
1052                   }
1053                   // TODO: compare annotation element rows
1054                   // TODO: compare props.
1055                 } else {
1056                   jan = getjAlignmentAnnotation(jal, an[j]);
1057                   jal.addAnnotation(jan);
1058                   bindjvvobj(jan, an[j]);
1059                 }
1060               }
1061             }
1062             AlignFrame alignFrame;
1063             if (av==null) {
1064               Cache.log.debug("New alignframe for alignment "+alignment.getVorbaId());
1065               // ///////////////////////////////
1066               // construct alignment view
1067               alignFrame = new AlignFrame(jal);
1068               av=alignFrame.getViewport();
1069               String title = alignment.getProvenance().getEntry(alignment.getProvenance().getEntryCount()-1).getAction();
1070               if (alignment.getPropertyCount()>0) {
1071                 for (int p=0,pe=alignment.getPropertyCount(); p<pe; p++) {
1072                   if (alignment.getProperty(p).getName().equals("jalview:AlTitle")) {
1073                     title = alignment.getProperty(p).getContent();
1074                   }
1075                 }
1076               }
1077               // TODO: automatically create meaningful title for a vamsas alignment using its provenance.
1078               jalview.gui.Desktop.addInternalFrame(alignFrame, title + "("+alignment.getVorbaId()+")",
1079                   AlignFrame.NEW_WINDOW_WIDTH,
1080                   AlignFrame.NEW_WINDOW_HEIGHT);
1081               bindjvvobj(av, alignment);
1082             } else {
1083               // find the alignFrame for jal.
1084               // TODO: fix this so we retrieve the alignFrame handing av *directly*
1085               alignFrame=getAlignFrameFor(av);
1086             }
1087             // LOAD TREES
1088             // /////////////////////////////////////
1089             if (alignment.getTreeCount() > 0)
1090             {
1091
1092               for (int t = 0; t < alignment.getTreeCount(); t++)
1093               {
1094                 Tree tree = alignment.getTree(t);
1095                 TreePanel tp=(TreePanel) getvObj2jv(tree);
1096                 if (tp!=null) {
1097                   Cache.log.info("Update from vamsas document to alignment associated tree not implemented yet.");
1098                 } else {
1099                   // make a new tree
1100                   Object[] idata = this.recoverInputData(tree.getProvenance());
1101                   try {
1102                     AlignmentView inputData=null;
1103                     if (idata!=null && idata[0]!=null)
1104                       inputData = (AlignmentView) idata[0];
1105                     tp = alignFrame.ShowNewickTree(
1106                         new jalview.io.NewickFile(tree.getNewick(0).getContent()),
1107                         tree.getNewick(0).getTitle()+" ("+tree.getVorbaId()+")",inputData,
1108                         600, 500,
1109                         t * 20 + 50, t * 20 + 50);
1110                     bindjvvobj(tp, tree);
1111                   } catch (Exception e) {
1112                     Cache.log.warn("Problems parsing treefile '"+tree.getNewick(0).getContent()+"'",e);
1113                   }
1114                 }
1115               }
1116             }
1117
1118           }
1119         }
1120       }
1121     }
1122   }
1123   // bitfields - should be a template in j1.5
1124   private static int HASSECSTR=0;
1125   private static int HASVALS=1;
1126   private static int HASHPHOB=2;
1127   private static int HASDC=3;
1128   private static int HASDESCSTR=4;
1129   private static int HASTWOSTATE=5; // not used yet.
1130   /**
1131    * parses the AnnotationElements - if they exist - into jalview.datamodel.Annotation[] rows
1132    * Two annotation rows are made if there are distinct annotation for both at 'pos' and 'after pos' at any particular site.
1133    * @param annotation
1134    * @return { boolean[static int constants ], int[ae.length] - map to annotated object frame, jalview.datamodel.Annotation[], jalview.datamodel.Annotation[] (after)}
1135    */
1136   private Object[] parseRangeAnnotation(org.vamsas.objects.core.RangeAnnotation annotation) {
1137     // set these attributes by looking in the annotation to decide what kind of alignment annotation rows will be made
1138     // TODO: potentially we might make several annotation rows from one vamsas alignment annotation. the jv2Vobj binding mechanism
1139     // may not quite cope with this (without binding an array of annotations to a vamsas alignment annotation)
1140     // summary flags saying what we found over the set of annotation rows.
1141     boolean[] AeContent = new boolean[] { false, false, false, false, false};
1142     int[] rangeMap = getMapping(annotation);
1143     jalview.datamodel.Annotation[][] anot=new jalview.datamodel.Annotation[][] { 
1144         new jalview.datamodel.Annotation[rangeMap.length],
1145         new jalview.datamodel.Annotation[rangeMap.length]
1146     };
1147     boolean mergeable=true; //false  if 'after positions cant be placed on same annotation row as positions. 
1148     
1149     if (annotation.getAnnotationElementCount()>0) {
1150       AnnotationElement ae[] = annotation.getAnnotationElement();
1151       for (int aa = 0; aa < ae.length; aa++)
1152       {
1153         int pos = ae[aa].getPosition()-1;// pos counts from 1 to (|seg.start-seg.end|+1)
1154         if (pos>=0 && pos<rangeMap.length) { 
1155           int row=ae[aa].getAfter()?1:0;
1156           if (anot[row][pos]!=null) {
1157             // only time this should happen is if the After flag is set.
1158             Cache.log.debug("Ignoring duplicate annotation site at "+pos);
1159             continue;
1160           }
1161           if (anot[1-row][pos]!=null)
1162             mergeable=false;
1163           String desc = "";
1164           if (ae[aa].getDescription()!=null) {
1165             desc = ae[aa].getDescription();
1166             if (desc.length()>0) {
1167               // have imported valid description string
1168               AeContent[HASDESCSTR]=true;
1169             }
1170           }
1171           String dc = null;//ae[aa].getDisplayCharacter()==null ? "dc" : ae[aa].getDisplayCharacter();
1172           String ss = null;//ae[aa].getSecondaryStructure()==null ? "ss" : ae[aa].getSecondaryStructure();
1173           java.awt.Color colour = null;
1174           if (ae[aa].getGlyphCount()>0) {
1175             Glyph[] glyphs = ae[aa].getGlyph();
1176             for (int g=0; g<glyphs.length; g++) {
1177               if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE)) {
1178                 ss=glyphs[g].getContent();
1179                 AeContent[HASSECSTR]=true;
1180               } else if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO)) {
1181                 Cache.log.debug("ignoring hydrophobicity glyph marker.");
1182                 AeContent[HASHPHOB]=true;
1183                 char c=(dc=glyphs[g].getContent()).charAt(0);
1184                 // dc may get overwritten - but we still set the colour.
1185                 colour = new java.awt.Color(c=='+'?255:0,c=='.'?255:0,c=='-'?255:0);
1186
1187               } else if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.DEFAULT)) {
1188                 dc = glyphs[g].getContent();
1189                 AeContent[HASDC]=true;
1190               } else {
1191                 Cache.log.debug("Ignoring unknown glyph type "+glyphs[g].getDict());
1192               }
1193             }
1194           }
1195           float val=0;
1196           if (ae[aa].getValueCount()>0) {
1197             AeContent[HASVALS]=true;
1198             if (ae[aa].getValueCount()>1) {
1199               Cache.log.warn("ignoring additional "+(ae[aa].getValueCount()-1)+"values in annotation element.");
1200             }
1201             val = ae[aa].getValue(0);
1202           }
1203           if (colour==null) {
1204             anot[row][pos]=new jalview.datamodel.Annotation((dc!=null) ? dc : "", desc, (ss!=null)?ss.charAt(0):' ', val);
1205           } else {
1206             anot[row][pos]=new jalview.datamodel.Annotation((dc!=null) ? dc : "", desc, (ss!=null)?ss.charAt(0):' ', val, colour);
1207           }
1208         } else {
1209           Cache.log.warn("Ignoring out of bound annotation element "+aa+" in "+annotation.getVorbaId().getId());
1210         }
1211       }
1212       // decide on how many annotation rows are needed.
1213       if (mergeable) {
1214         for (int i=0; i<anot[0].length;i++) {
1215           if (anot[1][i]!=null) {
1216             anot[0][i] = anot[1][i];
1217             anot[0][i].description = anot[0][i].description+" (after)";
1218             AeContent[HASDESCSTR]=true; // we have valid description string data
1219             anot[1][i] = null;
1220           }
1221         }
1222         anot[1] = null;
1223       } else {
1224         for (int i=0; i<anot[0].length;i++) {
1225           anot[1][i].description = anot[1][i].description+" (after)";
1226         }
1227       }
1228       return new Object[] { AeContent, rangeMap, anot[0], anot[1] };
1229     } else {
1230       // no annotations to parse. Just return an empty annotationElement[] array.
1231       return new Object[] { AeContent, rangeMap, anot[0], anot[1] };
1232     }
1233     // return null;
1234   }
1235   /**
1236    * @param jal the jalview alignment to which the annotation will be attached (ideally - freshly updated from corresponding vamsas alignment)
1237    * @param annotation
1238    * @return unbound jalview alignment annotation object.
1239    */
1240   private jalview.datamodel.AlignmentAnnotation getjAlignmentAnnotation(jalview.datamodel.AlignmentI jal, org.vamsas.objects.core.RangeAnnotation annotation) {
1241     jalview.datamodel.AlignmentAnnotation jan =null;
1242     if (annotation==null)
1243       return null;
1244     // boolean hasSequenceRef=annotation.getClass().equals(org.vamsas.objects.core.AlignmentSequenceAnnotation.class);
1245     //boolean hasProvenance=hasSequenceRef || (annotation.getClass().equals(org.vamsas.objects.core.AlignmentAnnotation.class));
1246     /*int se[] = getBounds(annotation);
1247     if (se==null)
1248       se=new int[] {0,jal.getWidth()-1};
1249      */
1250     Object[] parsedRangeAnnotation = parseRangeAnnotation(annotation);
1251     String a_label=annotation.getLabel();
1252     String a_descr=annotation.getDescription();
1253     if (a_label==null || a_label.length()==0) {
1254       a_label = annotation.getType();
1255       if (a_label.length()==0)
1256         a_label = "Unamed annotation";
1257     }
1258     if (a_descr==null || a_descr.length()==0) {
1259       a_descr = "Annotation of type '"+annotation.getType()+"'";
1260     }
1261     if (parsedRangeAnnotation==null) {
1262       Cache.log.debug("Inserting empty annotation row elements for a whole-alignment annotation.");
1263       
1264       
1265     } else {
1266       if (parsedRangeAnnotation[3]!=null) {
1267         Cache.log.warn("Ignoring 'After' annotation row in "+annotation.getVorbaId());
1268       }
1269       jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2];
1270       boolean[] has=(boolean[])parsedRangeAnnotation[0];
1271       // VAMSAS: getGraph is only on derived annotation for alignments - in this way its 'odd' - there is already an existing TODO about removing this flag as being redundant
1272       /*if ((annotation.getClass().equals(org.vamsas.objects.core.AlignmentAnnotation.class) && ((org.vamsas.objects.core.AlignmentAnnotation)annotation).getGraph())
1273           || (hasSequenceRef=true && ((org.vamsas.objects.core.AlignmentSequenceAnnotation)annotation).getGraph())) {
1274       */
1275       if (has[HASVALS]) {
1276         // make bounds and automatic description strings for jalview user's benefit (these shouldn't be written back to vamsas document)
1277         boolean first=true;
1278         float min=0,max=1;
1279         for (int i=0;i<arow.length; i++) {
1280           if (arow[i]!=null) {
1281             // check range - shouldn't we have a min and max property in the annotation object ?
1282             if (first) { min=max=arow[i].value; first=false;}
1283             else { if (arow[i].value<min) { min=arow[i].value; }
1284             else if (arow[i].value>max) { max=arow[i].value; }
1285             }
1286             // make tooltip and display char value
1287             if (!has[HASDESCSTR]) arow[i].description = arow[i].value + "";
1288             if (!has[HASDC]) arow[i].displayCharacter=arow[i].value+"";
1289           }
1290         }
1291         int type=jalview.datamodel.AlignmentAnnotation.LINE_GRAPH;
1292         if (has[HASHPHOB]) {
1293           type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH;
1294         }
1295         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow, min, max, type);
1296       } else {
1297         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow);
1298         jan.setThreshold(null);
1299       }
1300       if (annotation.getLinkCount()>0) {
1301         Cache.log.warn("Ignoring "+annotation.getLinkCount()+"links added to AlignmentAnnotation.");
1302       }
1303       if (annotation.getModifiable()) {
1304         jan.editable=true;
1305       }
1306
1307       if (annotation.getPropertyCount()>0) {
1308         // look for special jalview properties
1309         org.vamsas.objects.core.Property[] props=annotation.getProperty();
1310         for (int p=0;p<props.length; p++) {
1311           if (props[p].getName().equalsIgnoreCase("jalview:graphType")) {
1312             try { 
1313               // probably a jalview annotation graph so recover the visualization hints.
1314               jan.graph = jalview.datamodel.AlignmentAnnotation.getGraphValueFromString(props[p].getContent());
1315             } catch (Exception e) {
1316               Cache.log.debug("Invalid graph type value in jalview:graphType property.");
1317             }
1318             try {
1319               if (annotation.getGroup()!=null && annotation.getGroup().length()>0)
1320                 jan.graphGroup = Integer.parseInt(annotation.getGroup());
1321             } catch (Exception e) {
1322               Cache.log.info("UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");
1323             }
1324           }
1325         }
1326       }
1327
1328       return jan;
1329
1330     } 
1331
1332     return null;
1333   }
1334
1335   private SequenceFeature getJalviewSeqFeature(RangeAnnotation dseta) {
1336     int[] se = getBounds(dseta);
1337     SequenceFeature sf = new jalview.datamodel.SequenceFeature(dseta.getType(),
1338         dseta.getDescription(), dseta.getStatus(), se[0], se[1], dseta
1339         .getGroup());
1340     if (dseta.getLinkCount() > 0)
1341     {
1342       Link[] links = dseta.getLink();
1343       for (int i = 0; i < links.length; i++)
1344       {
1345         sf.addLink(links[i].getContent() + "|" + links[i].getHref());
1346       }
1347     }
1348     return sf;
1349   }
1350
1351   /**
1352    * get real bounds of a RangeType's specification. start and end are an
1353    * inclusive range within which all segments and positions lie.
1354    * TODO: refactor to vamsas utils
1355    * @param dseta
1356    * @return int[] { start, end}
1357    */
1358   private int[] getBounds(RangeType dseta) {
1359     if (dseta != null)
1360     {
1361       int[] se = null;
1362       if (dseta.getSegCount()>0 && dseta.getPosCount()>0)
1363         throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
1364       if (dseta.getSegCount() > 0)
1365       {
1366         se = getSegRange(dseta.getSeg(0),true);
1367         for (int s = 1, sSize = dseta.getSegCount(); s < sSize; s++)
1368         {
1369           int nse[] = getSegRange(dseta.getSeg(s), true);
1370           if (se[0] > nse[0])
1371             se[0] = nse[0];
1372           if (se[1] < nse[1])
1373             se[1] = nse[1];
1374         }
1375       }
1376       if (dseta.getPosCount() > 0)
1377       {
1378         // could do a polarity for pos range too. and pass back indication of discontinuities.
1379         int pos = dseta.getPos(0).getI();
1380         se = new int[] { pos, pos };
1381         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
1382         {
1383           pos = dseta.getPos(p).getI();
1384           if (se[0] > pos)
1385             se[0] = pos;
1386           if (se[1] < pos)
1387             se[1] = pos;
1388         }
1389       }
1390       return se;
1391     }
1392     return null;
1393   }
1394   /**
1395    * map from a rangeType's internal frame to the referenced object's coordinate frame.
1396    * @param dseta
1397    * @return int [] { ref(pos)...} for all pos in rangeType's frame.
1398    */
1399   private int[] getMapping(RangeType dseta) {
1400     Vector posList=new Vector();
1401     if (dseta != null)
1402     {
1403       int[] se = null;
1404       if (dseta.getSegCount()>0 && dseta.getPosCount()>0)
1405         throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
1406       if (dseta.getSegCount() > 0)
1407       {
1408         for (int s = 0, sSize = dseta.getSegCount(); s < sSize; s++)
1409         {
1410           se = getSegRange(dseta.getSeg(s), false);
1411           int se_end=se[1-se[2]]+(se[2]==0 ? 1 : -1);
1412           for (int p=se[se[2]]; p!=se_end; p+=se[2]==0 ? 1 : -1 ) {
1413             posList.add(new Integer(p));
1414           }
1415         }
1416       } 
1417       else if (dseta.getPosCount() > 0)
1418       {
1419         int pos = dseta.getPos(0).getI();
1420
1421         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
1422         {
1423           pos = dseta.getPos(p).getI();
1424           posList.add(new Integer(pos));
1425         }
1426       }
1427     }
1428     if (posList!=null && posList.size()>0) {
1429       int[] range=new int[posList.size()];
1430       for (int i=0; i<range.length; i++)
1431         range[i] = ((Integer)posList.elementAt(i)).intValue();
1432       posList.clear();
1433       return range;
1434     }
1435     return null;
1436   }
1437   /* not needed now. 
1438    * Provenance getVamsasProvenance(jalview.datamodel.Provenance jprov) {
1439     jalview.datamodel.ProvenanceEntry[] entries = null;
1440     // TODO: fix App and Action here.
1441     Provenance prov = new Provenance();
1442     org.exolab.castor.types.Date date = new org.exolab.castor.types.Date(
1443         new java.util.Date());
1444     Entry provEntry;
1445
1446     if (jprov != null)
1447     {
1448       entries = jprov.getEntries();
1449       for (int i = 0; i < entries.length; i++)
1450       {
1451         provEntry = new Entry();
1452         try
1453         {
1454           date = new org.exolab.castor.types.Date(entries[i].getDate());
1455         } catch (Exception ex)
1456         {
1457           ex.printStackTrace();
1458
1459           date = new org.exolab.castor.types.Date(entries[i].getDate());
1460         }
1461         provEntry.setDate(date);
1462         provEntry.setUser(entries[i].getUser());
1463         provEntry.setAction(entries[i].getAction());
1464         prov.addEntry(provEntry);
1465       }
1466     }
1467     else
1468     {
1469       provEntry = new Entry();
1470       provEntry.setDate(date);
1471       provEntry.setUser(System.getProperty("user.name")); // TODO: ext string
1472       provEntry.setApp("JVAPP"); // TODO: ext string
1473       provEntry.setAction(action);
1474       prov.addEntry(provEntry);
1475     }
1476
1477     return prov;
1478   }
1479    */
1480   jalview.datamodel.Provenance getJalviewProvenance(Provenance prov) {
1481     // TODO: fix App and Action entries and check use of provenance in jalview.
1482     jalview.datamodel.Provenance jprov = new jalview.datamodel.Provenance();
1483     for (int i = 0; i < prov.getEntryCount(); i++)
1484     {
1485       jprov.addEntry(prov.getEntry(i).getUser(), prov.getEntry(i).getAction(),
1486           prov.getEntry(i).getDate().toDate(), prov.getEntry(i).getId());
1487     }
1488
1489     return jprov;
1490   }
1491
1492   /**
1493    * 
1494    * @return default initial provenance list for a Jalview created vamsas
1495    *         object.
1496    */
1497   Provenance dummyProvenance() {
1498     return dummyProvenance(null);
1499   }
1500
1501   Entry dummyPEntry(String action) {
1502     Entry entry = new Entry();
1503     entry.setApp(this.provEntry.getApp());
1504     if (action != null)
1505       entry.setAction(action);
1506     else
1507       entry.setAction("created.");
1508     entry.setDate(new org.exolab.castor.types.Date(new java.util.Date()));
1509     entry.setUser(this.provEntry.getUser());
1510     return entry;
1511   }
1512
1513   Provenance dummyProvenance(String action) {
1514     Provenance prov = new Provenance();
1515     prov.addEntry(dummyPEntry(action));
1516     return prov;
1517   }
1518
1519   void addProvenance(Provenance p, String action) {
1520     p.addEntry(dummyPEntry(action));
1521   }
1522
1523 }