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