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