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