63a3e528f3f1134526e6e5057d5fe6ceee197af6
[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                 if (aa[i].graph!=jalview.datamodel.AlignmentAnnotation.NO_GRAPH)
443                   ae.addValue(aa[i].annotations[a].value);
444                 ae.setPosition(gapMap[a]+1); // position w.r.t. AlignmentSequence
445                 // symbols
446                 if (aa[i].annotations[a].secondaryStructure != ' ')
447                 {
448                   // we only write an annotation where it really exists.
449                   Glyph ss = new Glyph();
450                   ss
451                   .setDict(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
452                   ss.setContent(String
453                       .valueOf(aa[i].annotations[a].secondaryStructure));
454                   ae.addGlyph(ss);
455                 }
456                 an.addAnnotationElement(ae);
457               }
458             }
459             else
460             {
461               // update reference sequence Annotation
462               if (an.getModifiable())
463               {
464                 // verify existing alignment sequence annotation is up to date
465                 System.out.println("update alignment sequence annotation.");
466               }
467               else
468               {
469                 // verify existing alignment sequence annotation is up to date
470                 System.out
471                 .println("make new alignment sequence annotation if modification has happened.");
472               }
473             }
474           }
475           else
476           {
477             // add Alignment Annotation
478             org.vamsas.objects.core.AlignmentAnnotation an = (org.vamsas.objects.core.AlignmentAnnotation) getjv2vObj(aa[i]);
479             if (an == null)
480             {
481               an = new org.vamsas.objects.core.AlignmentAnnotation();
482               an.setType("jalview:AnnotationRow");
483               an.setDescription(aa[i].description);
484               alignment.addAlignmentAnnotation(an);
485               Seg vSeg = new Seg();
486               vSeg.setStart(1);
487               vSeg.setInclusive(true);
488               vSeg.setEnd(jal.getWidth());
489               an.addSeg(vSeg);
490               if (aa[i].graph > 0)
491                 an.setGraph(true); // aa[i].graph);
492               an.setLabel(aa[i].label);
493               an.setProvenance(dummyProvenance());
494               if (aa[i].graph!=aa[i].NO_GRAPH) {
495                 an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote -
496                 // originally we
497               // were going to
498               // store
499               // graphGroup in
500               // the Jalview
501               // specific
502               // bits.
503                 an.setGraph(true);
504               } else {
505                 an.setGraph(false);
506               }
507               AnnotationElement ae;
508
509               for (int a = 0; a < aa[i].annotations.length; a++)
510               {
511                 if ((aa[i] == null) || (aa[i].annotations[a] == null))
512                 {
513                   continue;
514                 }
515
516                 ae = new AnnotationElement();
517                 ae.setDescription(aa[i].annotations[a].description);
518                 ae.addGlyph(new Glyph());
519                 ae.getGlyph(0)
520                 .setContent(aa[i].annotations[a].displayCharacter); // assume
521                 // jax-b
522                 // takes
523                 // care
524                 // of
525                 // utf8
526                 // translation
527                 ae.addValue(aa[i].annotations[a].value);
528                 ae.setPosition(a+1);
529                 if (aa[i].annotations[a].secondaryStructure != ' ')
530                 {
531                   Glyph ss = new Glyph();
532                   ss
533                   .setDict(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);
534                   ss.setContent(String
535                       .valueOf(aa[i].annotations[a].secondaryStructure));
536                   ae.addGlyph(ss);
537                 }
538                 an.addAnnotationElement(ae);
539               }
540               if (aa[i].editable) {
541                 //an.addProperty(newProperty("jalview:editable", null, "true"));
542                 an.setModifiable(true);
543               }
544               if (aa[i].graph!=jalview.datamodel.AlignmentAnnotation.NO_GRAPH) {
545                 an.setGraph(true);
546                 an.setGroup(Integer.toString(aa[i].graphGroup));
547                 an.addProperty(newProperty("jalview:graphType",null,
548                     ((aa[i].graph==jalview.datamodel.AlignmentAnnotation.BAR_GRAPH) ? "BAR_GRAPH" : "LINE_GRAPH")));
549
550                 /** and on and on.. 
551                  vProperty=new Property();
552                   vProperty.setName("jalview:graphThreshhold");
553                   vProperty.setContent(aa[i].threshold);
554                  */
555
556               }
557             }
558             else
559             {
560               if (an.getModifiable())
561               {
562                 // verify annotation - update (perhaps)
563                 Cache.log.info("update alignment sequence annotation. not yet implemented.");
564               }
565               else
566               {
567                 // verify annotation - update (perhaps)
568                 Cache.log.info("updated alignment sequence annotation added.");
569               }
570             }
571           }
572         }
573       }
574       // /////////////////////////////////////////////////////
575
576       // //////////////////////////////////////////////
577       // /SAVE THE TREES
578       // /////////////////////////////////
579       // FIND ANY ASSOCIATED TREES
580       if (Desktop.desktop != null)
581       {
582         javax.swing.JInternalFrame[] frames = Desktop.desktop.getAllFrames();
583
584         for (int t = 0; t < frames.length; t++)
585         {
586           if (frames[t] instanceof TreePanel)
587           {
588             TreePanel tp = (TreePanel) frames[t];
589
590             if (tp.getAlignment() == jal)
591             {
592               Tree tree = (Tree) getjv2vObj(tp);
593               if (tree == null)
594               {
595                 tree = new Tree();
596                 bindjvvobj(tp, tree);
597                 tree.setTitle(tp.getTitle());
598                 Newick newick = new Newick();
599                 // TODO: translate sequenceI to leaf mappings to vamsas
600                 // references - see tree specification in schema.
601                 newick.setContent(tp.getTree().toString());
602                 newick.setTitle(tp.getTitle());
603                 tree.addNewick(newick);
604                 tree.setProvenance(makeTreeProvenance(jal, tp));
605                 alignment.addTree(tree);
606               }
607               else
608               {
609                 if (tree.getModifiable())
610                 {
611                   // verify any changes.
612                   System.out.println("Update tree in document.");
613                 }
614                 else
615                 {
616                   System.out
617                   .println("Add modified tree as new tree in document.");
618                 }
619               }
620             }
621           }
622         }
623       }
624       // Store Jalview specific stuff in the Jalview appData
625       // not implemented in the SimpleDoc interface.
626     }
627
628     catch (Exception ex)
629     {
630       ex.printStackTrace();
631     }
632
633   }
634
635   private Property newProperty(String name, String type, String content) {
636     Property vProperty=new Property();
637     vProperty.setName(name);
638     if (type!=null)
639       vProperty.setType(type);
640     else
641       vProperty.setType("String");
642     vProperty.setContent(content);
643     return vProperty;
644   }
645
646   /**
647    * correctly create a RangeAnnotation from a jalview sequence feature
648    * 
649    * @param dsa
650    *          (typically DataSetAnnotations or AlignmentSequenceAnnotation)
651    * @param feature
652    *          (the feature to be mapped from)
653    * @return
654    */
655   private RangeAnnotation getDSAnnotationFromJalview(RangeAnnotation dsa,
656       SequenceFeature feature) {
657     dsa.setType(feature.getType());
658     Seg vSeg = new Seg();
659     vSeg.setStart(feature.getBegin());
660     vSeg.setEnd(feature.getEnd());
661     vSeg.setInclusive(true);
662     dsa.addSeg(vSeg);
663     dsa.setDescription(feature.getDescription());
664     dsa.setStatus(feature.getStatus());
665     if (feature.links != null && feature.links.size() > 0)
666     {
667       for (int i = 0, iSize = feature.links.size(); i < iSize; i++)
668       {
669         String link = (String) feature.links.elementAt(i);
670         int sep = link.indexOf('|');
671         if (sep > -1)
672         {
673           Link vLink = new Link();
674           if (sep > 0)
675             vLink.setContent(link.substring(0, sep - 1));
676           else
677             vLink.setContent("");
678           vLink.setHref(link.substring(sep + 1)); // TODO: validate href.
679           dsa.addLink(vLink);
680         }
681       }
682     }
683     dsa.setGroup(feature.getFeatureGroup());
684     return dsa;
685   }
686
687   /**
688    * correctly creates provenance for trees calculated on an alignment by
689    * jalview.
690    * 
691    * @param jal
692    * @param tp
693    * @return
694    */
695   private Provenance makeTreeProvenance(AlignmentI jal, TreePanel tp) {
696     Provenance prov = new Provenance();
697     prov.addEntry(new Entry());
698     prov.getEntry(0).setAction("imported "+tp.getTitle());
699     prov.getEntry(0).setUser(provEntry.getUser());
700     prov.getEntry(0).setApp(provEntry.getApp());
701     prov.getEntry(0).setDate(provEntry.getDate());
702     if (tp.getTree().hasOriginalSequenceData())
703     {
704       Input vInput = new Input();
705       // LATER: check to see if tree input data is contained in this alignment -
706       // or just correctly resolve the tree's seqData to the correct alignment in
707       // the document.
708       vInput.setObjRef(getjv2vObj(jal));
709       prov.getEntry(0).setAction("created "+tp.getTitle());
710       prov.getEntry(0).addInput(vInput);
711       vInput.setName("jalview:seqdist");
712       prov.getEntry(0).addParam(new Param());
713       prov.getEntry(0).getParam(0).setName("treeType");
714       prov.getEntry(0).getParam(0).setType("utf8");
715       prov.getEntry(0).getParam(0).setContent("NJ");
716       
717       int ranges[] = tp.getTree().seqData.getVisibleContigs();
718       for (int r = 0; r < ranges.length; r += 2)
719       {
720         Seg visSeg = new Seg();
721         visSeg.setStart(ranges[r]);
722         visSeg.setEnd(ranges[r + 1]);
723         visSeg.setInclusive(true);
724         vInput.addSeg(visSeg);
725       }
726     }
727     return prov;
728   }
729
730   /**
731    * 
732    * @param tp
733    * @return Object[] { AlignmentView, AlignmentI - reference alignment for
734    *         input }
735    */
736   private Object[] recoverInputData(Provenance tp) {
737     for (int pe = 0; pe < tp.getEntryCount(); pe++)
738     {
739       if (tp.getEntry(pe).getInputCount() > 0)
740       {
741         if (tp.getEntry(pe).getInputCount() > 1)
742           Cache.log.warn("Ignoring additional input spec in provenance entry "
743               + tp.getEntry(pe).toString());
744         // LATER: deal sensibly with multiple inputs.
745         Input vInput = tp.getEntry(pe).getInput(0);
746         if (vInput.getObjRef() instanceof org.vamsas.objects.core.Alignment)
747         {
748           // recover an AlignmentView for the input data
749           AlignmentI jal = (AlignmentI) getvObj2jv((org.vamsas.client.Vobject) vInput
750               .getObjRef());
751           jalview.datamodel.CigarArray view = jal.getCompactAlignment();
752           int from = 0, to = jal.getWidth();
753           for (int r = 0, s = vInput.getSegCount(); r < s; r++)
754           {
755             Seg visSeg = vInput.getSeg(r);
756             int se[] = getSegRange(visSeg,true); // jalview doesn't do bidirection alignments yet.
757             if (to > se[1])
758               Cache.log.warn("Ignoring invalid segment in InputData spec.");
759             else
760             {
761               if (se[0] > from)
762               {
763                 view.deleteRange(from, se[0] - 1);
764               }
765               from = se[1] + 1;
766             }
767           }
768           if (from < to)
769           {
770             view.deleteRange(from, to); // final deletion - TODO: check off by
771             // one for to
772           }
773           return new Object[] { new AlignmentView(view), jal };
774         }
775       }
776     }
777     Cache.log.debug("Returning null for input data recovery from provenance.");
778     return null;
779   }
780
781   /**
782    * get start<end range of segment, adjusting for inclusivity flag and
783    * polarity.
784    *  
785    * @param visSeg
786    * @param ensureDirection when true - always ensure start is less than end.
787    * @return int[] { start, end, direction} where direction==1 for range running from end to start.
788    */
789   private int[] getSegRange(Seg visSeg, boolean ensureDirection) {
790     boolean incl = visSeg.getInclusive();
791     // adjust for inclusive flag.
792     int pol = (visSeg.getStart() <= visSeg.getEnd()) ? 1 : -1; // polarity of
793     // region.
794     int start = visSeg.getStart() + (incl ? 0 : pol);
795     int end = visSeg.getEnd() + (incl ? 0 : -pol);
796     if (ensureDirection && pol==-1)
797     {
798       // jalview doesn't deal with inverted ranges, yet.
799       int t = end;
800       end = start;
801       start = t;
802     }
803     return new int[] { start, end, pol<0 ? 1 : 0 };
804   }
805
806   /**
807    * 
808    * @param annotation
809    * @return true if annotation is not to be stored in document
810    */
811   private boolean isJalviewOnly(AlignmentAnnotation annotation) {
812     return annotation.label.equals("Quality")
813     || annotation.label.equals("Conservation")
814     || annotation.label.equals("Consensus");
815   }
816   /**
817    * This will return the first AlignFrame viewing AlignViewport av.
818    * It will break if there are more than one AlignFrames viewing a particular av.
819    * This also shouldn't be in the io package.
820    * @param av
821    * @return alignFrame for av
822    */
823   public AlignFrame getAlignFrameFor(AlignViewport av) {
824     if (Desktop.desktop != null)
825     {
826       javax.swing.JInternalFrame[] frames = Desktop.desktop.getAllFrames();
827
828       for (int t = 0; t < frames.length; t++)
829       {
830         if (frames[t] instanceof AlignFrame) {
831           if (((AlignFrame) frames[t]).getViewport()==av)
832             return (AlignFrame) frames[t];
833         }
834       }
835     }
836     return null;
837   }
838   public void updateToJalview() {
839     VAMSAS _roots[] = cdoc.getVamsasRoots();
840
841     for (int _root = 0; _root<_roots.length; _root++) {
842       VAMSAS root = _roots[_root];
843       boolean newds=false;
844       for (int _ds=0,_nds=root.getDataSetCount(); _ds<_nds; _ds++) {
845         // ///////////////////////////////////
846         // ///LOAD DATASET
847         DataSet dataset = root.getDataSet(_ds);
848         int i, iSize = dataset.getSequenceCount();
849         Vector dsseqs;
850         jalview.datamodel.Alignment jdataset = (jalview.datamodel.Alignment) getvObj2jv(dataset);
851         int jremain=0;
852         if (jdataset==null) {
853           Cache.log.debug("Initialising new jalview dataset fields");
854           newds=true;
855           dsseqs=new Vector();
856         } else {
857           Cache.log.debug("Update jalview dataset from vamsas.");
858           jremain=jdataset.getHeight();
859           dsseqs=jdataset.getSequences();
860         }
861
862         // TODO: test sequence merging - we preserve existing non vamsas
863         // sequences but add in any new vamsas ones, and don't yet update any
864         // sequence attributes
865         for (i = 0; i < iSize ; i++)
866         {
867           Sequence vdseq = dataset.getSequence(i);
868           jalview.datamodel.SequenceI dsseq = (SequenceI) getvObj2jv(vdseq);
869           if (dsseq!=null) {
870             if (!dsseq.getSequence().equals(vdseq.getSequence()))
871               throw new Error("Broken! - mismatch of dataset sequence and jalview internal dataset sequence.");
872             jremain--;
873           } else {
874             dsseq = new jalview.datamodel.Sequence(
875                 dataset.getSequence(i).getName(),
876                 dataset.getSequence(i).getSequence(),
877                 dataset.getSequence(i).getStart(),
878                 dataset.getSequence(i).getEnd()  );
879             bindjvvobj(dsseq, dataset.getSequence(i));
880             dsseq.setVamsasId(dataset.getSequence(i).getVorbaId().getId());
881             dsseqs.add(dsseq);
882           }
883           if (vdseq.getDbRefCount()>0) {
884             DbRef [] dbref = vdseq.getDbRef();
885             for(int db=0; db<dbref.length; db++)
886             {
887               jalview.datamodel.DBRefEntry dbr=(jalview.datamodel.DBRefEntry) getvObj2jv(dbref[db]);
888               if (dbr==null) {
889                 // add new dbref
890                 dsseq.addDBRef(dbr= new jalview.datamodel.DBRefEntry
891                     (
892                         dbref[db].getSource().toString(),
893                         dbref[db].getVersion().toString(),
894                         dbref[db].getAccessionId().toString()));
895                 bindjvvobj(dbr, dbref[db]);
896               }
897             }
898           }
899         }
900
901         if (newds) {
902           SequenceI[] seqs = new SequenceI[dsseqs.size()];
903           for (i=0,iSize=dsseqs.size(); i<iSize; i++) {
904             seqs[i]=(SequenceI) dsseqs.elementAt(i);
905             dsseqs.setElementAt(null, i);
906           }
907           jdataset = new jalview.datamodel.Alignment(seqs);
908           Cache.log.debug("New vamsas dataset imported into jalview.");
909           bindjvvobj(jdataset, dataset);
910         }
911         // ////////
912         // add any new dataset sequence feature annotations
913         if (dataset.getDataSetAnnotations() != null) {
914           for (int dsa = 0; dsa < dataset.getDataSetAnnotationsCount(); dsa++) {
915             DataSetAnnotations dseta=dataset.getDataSetAnnotations(dsa);
916             SequenceI dsSeq=(SequenceI) getvObj2jv((Vobject) dseta.getSeqRef());
917             if (dsSeq==null) {
918               jalview.bin.Cache.log.warn("Couldn't resolve jalview sequenceI for dataset object reference "+((Vobject)dataset.getDataSetAnnotations(dsa).getSeqRef()).getVorbaId().getId());
919             } else {
920               if (dseta.getAnnotationElementCount()==0) {
921                 jalview.datamodel.SequenceFeature sf=(jalview.datamodel.SequenceFeature) getvObj2jv(dseta);
922                 if (sf==null) {
923                   dsSeq.addSequenceFeature(sf=getJalviewSeqFeature(dseta));
924                   bindjvvobj(sf, dseta);
925                 }
926               } else {
927                 // TODO: deal with alignmentAnnotation style annotation
928                 // appearing on dataset sequences.
929                 // JBPNote: we could just add them to all alignments but
930                 // that may complicate cross references in the jalview
931                 // datamodel
932                 Cache.log.warn("Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");
933               }
934             }
935           }
936         }
937
938         if (dataset.getAlignmentCount()>0) {
939           // LOAD ALIGNMENTS from DATASET 
940
941           for (int al=0,nal=dataset.getAlignmentCount(); al<nal; al++) {
942             org.vamsas.objects.core.Alignment alignment = dataset.getAlignment(al);
943             AlignViewport av = (AlignViewport) getvObj2jv(alignment);
944             jalview.datamodel.AlignmentI jal=null;
945             if (av!=null)
946               jal = av.getAlignment(); 
947             iSize = alignment.getAlignmentSequenceCount();
948             boolean newal=(jal==null) ? true : false;
949             Vector newasAnnots=new Vector();
950             char gapChar=' '; // default for new alignments read in from the document
951             if (jal!=null) {
952               dsseqs=jal.getSequences(); // for merge/update
953               gapChar=jal.getGapCharacter();
954             } else {
955               dsseqs=new Vector();
956             }
957             char valGapchar=alignment.getGapChar().charAt(0);
958             for (i = 0; i < iSize; i++)
959             {
960               AlignmentSequence valseq = alignment.getAlignmentSequence(i);
961               jalview.datamodel.SequenceI alseq = (SequenceI) getvObj2jv(valseq);
962               if (alseq!=null) {
963                 //TODO: upperCase/LowerCase situation here ? do we allow it ?
964                 //if (!alseq.getSequence().equals(valseq.getSequence())) {
965                 // throw new Error("Broken! - mismatch of dataset sequence and jalview internal dataset sequence.");
966                 if (Cache.log.isDebugEnabled())
967                   Cache.log.debug("Updating apparently edited sequence "+alseq.getName());
968                 // this might go *horribly* wrong
969                 alseq.setSequence(new String(valseq.getSequence()).replace(valGapchar, gapChar));
970                 jremain--;
971               } else {
972                 alseq = new jalview.datamodel.Sequence(
973                     valseq.getName(),
974                     valseq.getSequence().replace(valGapchar, gapChar),
975                     valseq.getStart(),
976                     valseq.getEnd()  );
977                 
978                 Vobject datsetseq = (Vobject)valseq.getRefid();
979                 if (datsetseq!=null) {
980                   alseq.setDatasetSequence((SequenceI)getvObj2jv(datsetseq)); // exceptions if AlignemntSequence reference isn't a simple SequenceI
981                 } else {
982                   Cache.log.error("Invalid dataset sequence id (null) for alignment sequence "+valseq.getVorbaId());
983                 }
984                 bindjvvobj(alseq, valseq);
985                 alseq.setVamsasId(valseq.getVorbaId().getId());
986                 dsseqs.add(alseq);
987               }
988               if (valseq.getAlignmentSequenceAnnotationCount()>0) {
989                 AlignmentSequenceAnnotation[] vasannot=valseq.getAlignmentSequenceAnnotation();
990                 for (int a=0; a<vasannot.length; a++) {
991                   jalview.datamodel.AlignmentAnnotation asa = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(vasannot[a]); // TODO: 1:many jalview alignment sequence annotations
992                   if (asa==null) {
993                     int se[] = getBounds(vasannot[a]);
994                     asa = getjAlignmentAnnotation(jal, vasannot[a]);
995                     asa.sequenceRef=alseq;
996                     asa.createSequenceMapping(alseq, alseq.getStart()+se[0], false); // TODO: verify that positions in alseqAnnotation correspond to ungapped residue positions.
997                     bindjvvobj(asa, vasannot[a]);
998                     newasAnnots.add(asa);
999                   } else {
1000                     // update existing annotation - can do this in place
1001                     if (vasannot[a].getModifiable()) {
1002                       Cache.log.info("UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");
1003                       // TODO: should at least replace with new one - otherwise things will break
1004                       // basically do this:
1005                       // int se[] = getBounds(vasannot[a]);
1006                       // asa.update(getjAlignmentAnnotation(jal, vasannot[a])); //  update from another annotation object in place.
1007                       // asa.createSequenceMapping(alseq, se[0], false); 
1008
1009                     }
1010                   }
1011                 }
1012               }
1013             }
1014             if (jal==null) {
1015               SequenceI[] seqs = new SequenceI[dsseqs.size()];
1016               for (i=0,iSize=dsseqs.size(); i<iSize; i++) {
1017                 seqs[i]=(SequenceI) dsseqs.elementAt(i);
1018                 dsseqs.setElementAt(null, i);
1019               }
1020               jal = new jalview.datamodel.Alignment(seqs);
1021               Cache.log.debug("New vamsas alignment imported into jalview "+alignment.getVorbaId().getId());
1022               jal.setDataset(jdataset);
1023             }
1024             if (newasAnnots!=null && newasAnnots.size()>0) {
1025               // Add the new sequence annotations in to the alignment.
1026               for (int an=0,anSize=newasAnnots.size(); an<anSize; an++) {
1027                 jal.addAnnotation((AlignmentAnnotation) newasAnnots.elementAt(an));
1028                 // TODO: check if anything has to be done - like calling adjustForAlignment or something.
1029                 newasAnnots.setElementAt(null, an);
1030               }
1031               newasAnnots=null;
1032             }
1033             // //////////////////////////////////////////
1034             // //LOAD ANNOTATIONS FOR THE ALIGNMENT
1035             // ////////////////////////////////////
1036             if (alignment.getAlignmentAnnotationCount()>0)
1037             {
1038               org.vamsas.objects.core.AlignmentAnnotation[] an = alignment.getAlignmentAnnotation();
1039
1040               for (int j = 0; j < an.length; j++)
1041               {
1042                 jalview.datamodel.AlignmentAnnotation jan=(jalview.datamodel.AlignmentAnnotation) getvObj2jv(an[j]);
1043                 if (jan!=null) {
1044                   // update or stay the same.
1045                   // TODO: should at least replace with a new one - otherwise things will break
1046                   // basically do this:
1047                   // jan.update(getjAlignmentAnnotation(jal, an[a])); //  update from another annotation object in place.
1048
1049                   Cache.log.debug("update from vamsas alignment annotation to existing jalview alignment annotation.");
1050                   if (an[j].getModifiable()) {
1051                     // TODO: user defined annotation is totally mutable... - so load it up or throw away if locally edited.
1052                     Cache.log.info("NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");
1053                   }
1054                   // TODO: compare annotation element rows
1055                   // TODO: compare props.
1056                 } else {
1057                   jan = getjAlignmentAnnotation(jal, an[j]);
1058                   jal.addAnnotation(jan);
1059                   bindjvvobj(jan, an[j]);
1060                 }
1061               }
1062             }
1063             AlignFrame alignFrame;
1064             if (av==null) {
1065               Cache.log.debug("New alignframe for alignment "+alignment.getVorbaId());
1066               // ///////////////////////////////
1067               // construct alignment view
1068               alignFrame = new AlignFrame(jal);
1069               av=alignFrame.getViewport();
1070               String title = alignment.getProvenance().getEntry(alignment.getProvenance().getEntryCount()-1).getAction();
1071               if (alignment.getPropertyCount()>0) {
1072                 for (int p=0,pe=alignment.getPropertyCount(); p<pe; p++) {
1073                   if (alignment.getProperty(p).getName().equals("jalview:AlTitle")) {
1074                     title = alignment.getProperty(p).getContent();
1075                   }
1076                 }
1077               }
1078               // TODO: automatically create meaningful title for a vamsas alignment using its provenance.
1079               jalview.gui.Desktop.addInternalFrame(alignFrame, title + "("+alignment.getVorbaId()+")",
1080                   AlignFrame.NEW_WINDOW_WIDTH,
1081                   AlignFrame.NEW_WINDOW_HEIGHT);
1082               bindjvvobj(av, alignment);
1083             } else {
1084               // find the alignFrame for jal.
1085               // TODO: fix this so we retrieve the alignFrame handing av *directly*
1086               alignFrame=getAlignFrameFor(av);
1087             }
1088             // LOAD TREES
1089             // /////////////////////////////////////
1090             if (alignment.getTreeCount() > 0)
1091             {
1092
1093               for (int t = 0; t < alignment.getTreeCount(); t++)
1094               {
1095                 Tree tree = alignment.getTree(t);
1096                 TreePanel tp=(TreePanel) getvObj2jv(tree);
1097                 if (tp!=null) {
1098                   Cache.log.info("Update from vamsas document to alignment associated tree not implemented yet.");
1099                 } else {
1100                   // make a new tree
1101                   Object[] idata = this.recoverInputData(tree.getProvenance());
1102                   try {
1103                     AlignmentView inputData=null;
1104                     if (idata!=null && idata[0]!=null)
1105                       inputData = (AlignmentView) idata[0];
1106                     tp = alignFrame.ShowNewickTree(
1107                         new jalview.io.NewickFile(tree.getNewick(0).getContent()),
1108                         tree.getNewick(0).getTitle()+" ("+tree.getVorbaId()+")",inputData,
1109                         600, 500,
1110                         t * 20 + 50, t * 20 + 50);
1111                     bindjvvobj(tp, tree);
1112                   } catch (Exception e) {
1113                     Cache.log.warn("Problems parsing treefile '"+tree.getNewick(0).getContent()+"'",e);
1114                   }
1115                 }
1116               }
1117             }
1118
1119           }
1120         }
1121       }
1122     }
1123   }
1124   // bitfields - should be a template in j1.5
1125   private static int HASSECSTR=0;
1126   private static int HASVALS=1;
1127   private static int HASHPHOB=2;
1128   private static int HASDC=3;
1129   private static int HASDESCSTR=4;
1130   private static int HASTWOSTATE=5; // not used yet.
1131   /**
1132    * parses the AnnotationElements - if they exist - into jalview.datamodel.Annotation[] rows
1133    * Two annotation rows are made if there are distinct annotation for both at 'pos' and 'after pos' at any particular site.
1134    * @param annotation
1135    * @return { boolean[static int constants ], int[ae.length] - map to annotated object frame, jalview.datamodel.Annotation[], jalview.datamodel.Annotation[] (after)}
1136    */
1137   private Object[] parseRangeAnnotation(org.vamsas.objects.core.RangeAnnotation annotation) {
1138     // set these attributes by looking in the annotation to decide what kind of alignment annotation rows will be made
1139     // TODO: potentially we might make several annotation rows from one vamsas alignment annotation. the jv2Vobj binding mechanism
1140     // may not quite cope with this (without binding an array of annotations to a vamsas alignment annotation)
1141     // summary flags saying what we found over the set of annotation rows.
1142     boolean[] AeContent = new boolean[] { false, false, false, false, false};
1143     int[] rangeMap = getMapping(annotation);
1144     jalview.datamodel.Annotation[][] anot=new jalview.datamodel.Annotation[][] { 
1145         new jalview.datamodel.Annotation[rangeMap.length],
1146         new jalview.datamodel.Annotation[rangeMap.length]
1147     };
1148     boolean mergeable=true; //false  if 'after positions cant be placed on same annotation row as positions. 
1149     
1150     if (annotation.getAnnotationElementCount()>0) {
1151       AnnotationElement ae[] = annotation.getAnnotationElement();
1152       for (int aa = 0; aa < ae.length; aa++)
1153       {
1154         int pos = ae[aa].getPosition()-1;// pos counts from 1 to (|seg.start-seg.end|+1)
1155         if (pos>=0 && pos<rangeMap.length) { 
1156           int row=ae[aa].getAfter()?1:0;
1157           if (anot[row][pos]!=null) {
1158             // only time this should happen is if the After flag is set.
1159             Cache.log.debug("Ignoring duplicate annotation site at "+pos);
1160             continue;
1161           }
1162           if (anot[1-row][pos]!=null)
1163             mergeable=false;
1164           String desc = "";
1165           if (ae[aa].getDescription()!=null) {
1166             desc = ae[aa].getDescription();
1167             if (desc.length()>0) {
1168               // have imported valid description string
1169               AeContent[HASDESCSTR]=true;
1170             }
1171           }
1172           String dc = null;//ae[aa].getDisplayCharacter()==null ? "dc" : ae[aa].getDisplayCharacter();
1173           String ss = null;//ae[aa].getSecondaryStructure()==null ? "ss" : ae[aa].getSecondaryStructure();
1174           java.awt.Color colour = null;
1175           if (ae[aa].getGlyphCount()>0) {
1176             Glyph[] glyphs = ae[aa].getGlyph();
1177             for (int g=0; g<glyphs.length; g++) {
1178               if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE)) {
1179                 ss=glyphs[g].getContent();
1180                 AeContent[HASSECSTR]=true;
1181               } else if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO)) {
1182                 Cache.log.debug("ignoring hydrophobicity glyph marker.");
1183                 AeContent[HASHPHOB]=true;
1184                 char c=(dc=glyphs[g].getContent()).charAt(0);
1185                 // dc may get overwritten - but we still set the colour.
1186                 colour = new java.awt.Color(c=='+'?255:0,c=='.'?255:0,c=='-'?255:0);
1187
1188               } else if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.DEFAULT)) {
1189                 dc = glyphs[g].getContent();
1190                 AeContent[HASDC]=true;
1191               } else {
1192                 Cache.log.debug("Ignoring unknown glyph type "+glyphs[g].getDict());
1193               }
1194             }
1195           }
1196           float val=0;
1197           if (ae[aa].getValueCount()>0) {
1198             AeContent[HASVALS]=true;
1199             if (ae[aa].getValueCount()>1) {
1200               Cache.log.warn("ignoring additional "+(ae[aa].getValueCount()-1)+"values in annotation element.");
1201             }
1202             val = ae[aa].getValue(0);
1203           }
1204           if (colour==null) {
1205             anot[row][pos]=new jalview.datamodel.Annotation((dc!=null) ? dc : "", desc, (ss!=null)?ss.charAt(0):' ', val);
1206           } else {
1207             anot[row][pos]=new jalview.datamodel.Annotation((dc!=null) ? dc : "", desc, (ss!=null)?ss.charAt(0):' ', val, colour);
1208           }
1209         } else {
1210           Cache.log.warn("Ignoring out of bound annotation element "+aa+" in "+annotation.getVorbaId().getId());
1211         }
1212       }
1213       // decide on how many annotation rows are needed.
1214       if (mergeable) {
1215         for (int i=0; i<anot[0].length;i++) {
1216           if (anot[1][i]!=null) {
1217             anot[0][i] = anot[1][i];
1218             anot[0][i].description = anot[0][i].description+" (after)";
1219             AeContent[HASDESCSTR]=true; // we have valid description string data
1220             anot[1][i] = null;
1221           }
1222         }
1223         anot[1] = null;
1224       } else {
1225         for (int i=0; i<anot[0].length;i++) {
1226           anot[1][i].description = anot[1][i].description+" (after)";
1227         }
1228       }
1229       return new Object[] { AeContent, rangeMap, anot[0], anot[1] };
1230     } else {
1231       // no annotations to parse. Just return an empty annotationElement[] array.
1232       return new Object[] { AeContent, rangeMap, anot[0], anot[1] };
1233     }
1234     // return null;
1235   }
1236   /**
1237    * @param jal the jalview alignment to which the annotation will be attached (ideally - freshly updated from corresponding vamsas alignment)
1238    * @param annotation
1239    * @return unbound jalview alignment annotation object.
1240    */
1241   private jalview.datamodel.AlignmentAnnotation getjAlignmentAnnotation(jalview.datamodel.AlignmentI jal, org.vamsas.objects.core.RangeAnnotation annotation) {
1242     jalview.datamodel.AlignmentAnnotation jan =null;
1243     if (annotation==null)
1244       return null;
1245     // boolean hasSequenceRef=annotation.getClass().equals(org.vamsas.objects.core.AlignmentSequenceAnnotation.class);
1246     //boolean hasProvenance=hasSequenceRef || (annotation.getClass().equals(org.vamsas.objects.core.AlignmentAnnotation.class));
1247     /*int se[] = getBounds(annotation);
1248     if (se==null)
1249       se=new int[] {0,jal.getWidth()-1};
1250      */
1251     Object[] parsedRangeAnnotation = parseRangeAnnotation(annotation);
1252     String a_label=annotation.getLabel();
1253     String a_descr=annotation.getDescription();
1254     if (a_label==null || a_label.length()==0) {
1255       a_label = annotation.getType();
1256       if (a_label.length()==0)
1257         a_label = "Unamed annotation";
1258     }
1259     if (a_descr==null || a_descr.length()==0) {
1260       a_descr = "Annotation of type '"+annotation.getType()+"'";
1261     }
1262     if (parsedRangeAnnotation==null) {
1263       Cache.log.debug("Inserting empty annotation row elements for a whole-alignment annotation.");
1264       
1265       
1266     } else {
1267       if (parsedRangeAnnotation[3]!=null) {
1268         Cache.log.warn("Ignoring 'After' annotation row in "+annotation.getVorbaId());
1269       }
1270       jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2];
1271       boolean[] has=(boolean[])parsedRangeAnnotation[0];
1272       // 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
1273       /*if ((annotation.getClass().equals(org.vamsas.objects.core.AlignmentAnnotation.class) && ((org.vamsas.objects.core.AlignmentAnnotation)annotation).getGraph())
1274           || (hasSequenceRef=true && ((org.vamsas.objects.core.AlignmentSequenceAnnotation)annotation).getGraph())) {
1275       */
1276       if (has[HASVALS]) {
1277         // make bounds and automatic description strings for jalview user's benefit (these shouldn't be written back to vamsas document)
1278         boolean first=true;
1279         float min=0,max=1;
1280         for (int i=0;i<arow.length; i++) {
1281           if (arow[i]!=null) {
1282             // check range - shouldn't we have a min and max property in the annotation object ?
1283             if (first) { min=max=arow[i].value; first=false;}
1284             else { if (arow[i].value<min) { min=arow[i].value; }
1285             else if (arow[i].value>max) { max=arow[i].value; }
1286             }
1287             // make tooltip and display char value
1288             if (!has[HASDESCSTR]) arow[i].description = arow[i].value + "";
1289             if (!has[HASDC]) arow[i].displayCharacter=arow[i].value+"";
1290           }
1291         }
1292         int type=jalview.datamodel.AlignmentAnnotation.LINE_GRAPH;
1293         if (has[HASHPHOB]) {
1294           type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH;
1295         }
1296         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow, min, max, type);
1297       } else {
1298         jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow);
1299         jan.setThreshold(null);
1300       }
1301       if (annotation.getLinkCount()>0) {
1302         Cache.log.warn("Ignoring "+annotation.getLinkCount()+"links added to AlignmentAnnotation.");
1303       }
1304       if (annotation.getModifiable()) {
1305         jan.editable=true;
1306       }
1307
1308       if (annotation.getPropertyCount()>0) {
1309         // look for special jalview properties
1310         org.vamsas.objects.core.Property[] props=annotation.getProperty();
1311         for (int p=0;p<props.length; p++) {
1312           if (props[p].getName().equalsIgnoreCase("jalview:graphType")) {
1313             try { 
1314               // probably a jalview annotation graph so recover the visualization hints.
1315               jan.graph = jalview.datamodel.AlignmentAnnotation.getGraphValueFromString(props[p].getContent());
1316             } catch (Exception e) {
1317               Cache.log.debug("Invalid graph type value in jalview:graphType property.");
1318             }
1319             try {
1320               if (annotation.getGroup()!=null && annotation.getGroup().length()>0)
1321                 jan.graphGroup = Integer.parseInt(annotation.getGroup());
1322             } catch (Exception e) {
1323               Cache.log.info("UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");
1324             }
1325           }
1326         }
1327       }
1328
1329       return jan;
1330
1331     } 
1332
1333     return null;
1334   }
1335
1336   private SequenceFeature getJalviewSeqFeature(RangeAnnotation dseta) {
1337     int[] se = getBounds(dseta);
1338     SequenceFeature sf = new jalview.datamodel.SequenceFeature(dseta.getType(),
1339         dseta.getDescription(), dseta.getStatus(), se[0], se[1], dseta
1340         .getGroup());
1341     if (dseta.getLinkCount() > 0)
1342     {
1343       Link[] links = dseta.getLink();
1344       for (int i = 0; i < links.length; i++)
1345       {
1346         sf.addLink(links[i].getContent() + "|" + links[i].getHref());
1347       }
1348     }
1349     return sf;
1350   }
1351
1352   /**
1353    * get real bounds of a RangeType's specification. start and end are an
1354    * inclusive range within which all segments and positions lie.
1355    * TODO: refactor to vamsas utils
1356    * @param dseta
1357    * @return int[] { start, end}
1358    */
1359   private int[] getBounds(RangeType dseta) {
1360     if (dseta != null)
1361     {
1362       int[] se = null;
1363       if (dseta.getSegCount()>0 && dseta.getPosCount()>0)
1364         throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
1365       if (dseta.getSegCount() > 0)
1366       {
1367         se = getSegRange(dseta.getSeg(0),true);
1368         for (int s = 1, sSize = dseta.getSegCount(); s < sSize; s++)
1369         {
1370           int nse[] = getSegRange(dseta.getSeg(s), true);
1371           if (se[0] > nse[0])
1372             se[0] = nse[0];
1373           if (se[1] < nse[1])
1374             se[1] = nse[1];
1375         }
1376       }
1377       if (dseta.getPosCount() > 0)
1378       {
1379         // could do a polarity for pos range too. and pass back indication of discontinuities.
1380         int pos = dseta.getPos(0).getI();
1381         se = new int[] { pos, pos };
1382         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
1383         {
1384           pos = dseta.getPos(p).getI();
1385           if (se[0] > pos)
1386             se[0] = pos;
1387           if (se[1] < pos)
1388             se[1] = pos;
1389         }
1390       }
1391       return se;
1392     }
1393     return null;
1394   }
1395   /**
1396    * map from a rangeType's internal frame to the referenced object's coordinate frame.
1397    * @param dseta
1398    * @return int [] { ref(pos)...} for all pos in rangeType's frame.
1399    */
1400   private int[] getMapping(RangeType dseta) {
1401     Vector posList=new Vector();
1402     if (dseta != null)
1403     {
1404       int[] se = null;
1405       if (dseta.getSegCount()>0 && dseta.getPosCount()>0)
1406         throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");
1407       if (dseta.getSegCount() > 0)
1408       {
1409         for (int s = 0, sSize = dseta.getSegCount(); s < sSize; s++)
1410         {
1411           se = getSegRange(dseta.getSeg(s), false);
1412           int se_end=se[1-se[2]]+(se[2]==0 ? 1 : -1);
1413           for (int p=se[se[2]]; p!=se_end; p+=se[2]==0 ? 1 : -1 ) {
1414             posList.add(new Integer(p));
1415           }
1416         }
1417       } 
1418       else if (dseta.getPosCount() > 0)
1419       {
1420         int pos = dseta.getPos(0).getI();
1421
1422         for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)
1423         {
1424           pos = dseta.getPos(p).getI();
1425           posList.add(new Integer(pos));
1426         }
1427       }
1428     }
1429     if (posList!=null && posList.size()>0) {
1430       int[] range=new int[posList.size()];
1431       for (int i=0; i<range.length; i++)
1432         range[i] = ((Integer)posList.elementAt(i)).intValue();
1433       posList.clear();
1434       return range;
1435     }
1436     return null;
1437   }
1438   /* not needed now. 
1439    * Provenance getVamsasProvenance(jalview.datamodel.Provenance jprov) {
1440     jalview.datamodel.ProvenanceEntry[] entries = null;
1441     // TODO: fix App and Action here.
1442     Provenance prov = new Provenance();
1443     org.exolab.castor.types.Date date = new org.exolab.castor.types.Date(
1444         new java.util.Date());
1445     Entry provEntry;
1446
1447     if (jprov != null)
1448     {
1449       entries = jprov.getEntries();
1450       for (int i = 0; i < entries.length; i++)
1451       {
1452         provEntry = new Entry();
1453         try
1454         {
1455           date = new org.exolab.castor.types.Date(entries[i].getDate());
1456         } catch (Exception ex)
1457         {
1458           ex.printStackTrace();
1459
1460           date = new org.exolab.castor.types.Date(entries[i].getDate());
1461         }
1462         provEntry.setDate(date);
1463         provEntry.setUser(entries[i].getUser());
1464         provEntry.setAction(entries[i].getAction());
1465         prov.addEntry(provEntry);
1466       }
1467     }
1468     else
1469     {
1470       provEntry = new Entry();
1471       provEntry.setDate(date);
1472       provEntry.setUser(System.getProperty("user.name")); // TODO: ext string
1473       provEntry.setApp("JVAPP"); // TODO: ext string
1474       provEntry.setAction(action);
1475       prov.addEntry(provEntry);
1476     }
1477
1478     return prov;
1479   }
1480    */
1481   jalview.datamodel.Provenance getJalviewProvenance(Provenance prov) {
1482     // TODO: fix App and Action entries and check use of provenance in jalview.
1483     jalview.datamodel.Provenance jprov = new jalview.datamodel.Provenance();
1484     for (int i = 0; i < prov.getEntryCount(); i++)
1485     {
1486       jprov.addEntry(prov.getEntry(i).getUser(), prov.getEntry(i).getAction(),
1487           prov.getEntry(i).getDate().toDate(), prov.getEntry(i).getId());
1488     }
1489
1490     return jprov;
1491   }
1492
1493   /**
1494    * 
1495    * @return default initial provenance list for a Jalview created vamsas
1496    *         object.
1497    */
1498   Provenance dummyProvenance() {
1499     return dummyProvenance(null);
1500   }
1501
1502   Entry dummyPEntry(String action) {
1503     Entry entry = new Entry();
1504     entry.setApp(this.provEntry.getApp());
1505     if (action != null)
1506       entry.setAction(action);
1507     else
1508       entry.setAction("created.");
1509     entry.setDate(new org.exolab.castor.types.Date(new java.util.Date()));
1510     entry.setUser(this.provEntry.getUser());
1511     return entry;
1512   }
1513
1514   Provenance dummyProvenance(String action) {
1515     Provenance prov = new Provenance();
1516     prov.addEntry(dummyPEntry(action));
1517     return prov;
1518   }
1519
1520   void addProvenance(Provenance p, String action) {
1521     p.addEntry(dummyPEntry(action));
1522   }
1523
1524 }