imported Vamsas bindings and alpha vamsas client code from VamJalview cvs branch...
[jalview.git] / src / jalview / io / VamsasDatastore.java
diff --git a/src/jalview/io/VamsasDatastore.java b/src/jalview/io/VamsasDatastore.java
new file mode 100755 (executable)
index 0000000..395a251
--- /dev/null
@@ -0,0 +1,1552 @@
+/*\r
+ * Jalview - A Sequence Alignment Editor and Viewer\r
+ * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle\r
+ *\r
+ * This program is free software; you can redistribute it and/or\r
+ * modify it under the terms of the GNU General Public License\r
+ * as published by the Free Software Foundation; either version 2\r
+ * of the License, or (at your option) any later version.\r
+ *\r
+ * This program is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with this program; if not, write to the Free Software\r
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\r
+ */\r
+\r
+package jalview.io;\r
+\r
+import org.vamsas.client.Vobject;\r
+import org.vamsas.client.VorbaId;\r
+import org.vamsas.objects.core.*;\r
+import org.vamsas.objects.utils.DocumentStuff;\r
+import org.vamsas.test.simpleclient.ClientDoc;\r
+\r
+import jalview.bin.Cache;\r
+import jalview.datamodel.AlignmentAnnotation;\r
+import jalview.datamodel.AlignmentI;\r
+import jalview.datamodel.AlignmentView;\r
+import jalview.datamodel.DBRefEntry;\r
+import jalview.datamodel.SequenceFeature;\r
+import jalview.datamodel.SequenceI;\r
+import jalview.gui.*;\r
+\r
+import java.io.*;\r
+import java.util.HashMap;\r
+import java.util.HashSet;\r
+import java.util.Hashtable;\r
+import java.util.IdentityHashMap;\r
+import java.util.Vector;\r
+import java.util.jar.*;\r
+import org.exolab.castor.xml.*;\r
+import org.exolab.castor.mapping.Mapping;\r
+\r
+/*\r
+ * \r
+ * static {\r
+ * org.exolab.castor.util.LocalConfiguration.getInstance().getProperties().setProperty(\r
+ * "org.exolab.castor.serializer", "org.apache.xml.serialize.XMLSerilazizer"); }\r
+ * \r
+ */\r
+\r
+public class VamsasDatastore {\r
+  Entry provEntry = null;\r
+\r
+  // AlignViewport av;\r
+\r
+  org.exolab.castor.types.Date date = new org.exolab.castor.types.Date(\r
+      new java.util.Date());\r
+\r
+  ClientDoc cdoc;\r
+\r
+  Hashtable vobj2jv;\r
+\r
+  IdentityHashMap jv2vobj;\r
+\r
+  public VamsasDatastore(ClientDoc cdoc, Hashtable vobj2jv,\r
+      IdentityHashMap jv2vobj, Entry provEntry) {\r
+      this.cdoc = cdoc;\r
+    this.vobj2jv = vobj2jv;\r
+    this.jv2vobj = jv2vobj;\r
+    this.provEntry = provEntry;\r
+  }\r
+\r
+  /*\r
+   * public void storeJalview(String file, AlignFrame af) { try { // 1. Load the\r
+   * mapping information from the file Mapping map = new\r
+   * Mapping(getClass().getClassLoader()); java.net.URL url =\r
+   * getClass().getResource("/jalview_mapping.xml"); map.loadMapping(url); // 2.\r
+   * Unmarshal the data // Unmarshaller unmar = new Unmarshaller();\r
+   * //unmar.setIgnoreExtraElements(true); //unmar.setMapping(map); // uni =\r
+   * (UniprotFile) unmar.unmarshal(new FileReader(file)); // 3. marshal the data\r
+   * with the total price back and print the XML in the console Marshaller\r
+   * marshaller = new Marshaller( new FileWriter(file) );\r
+   * \r
+   * marshaller.setMapping(map); marshaller.marshal(af); } catch (Exception e) {\r
+   * e.printStackTrace(); } }\r
+   * \r
+   * \r
+   */\r
+  /**\r
+   * @return the Vobject bound to Jalview datamodel object\r
+   */\r
+  protected Vobject getjv2vObj(Object jvobj) {\r
+    if (jv2vobj.containsKey(jvobj))\r
+      return cdoc.getObject((VorbaId) jv2vobj.get(jvobj));\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * \r
+   * @param vobj\r
+   * @return Jalview datamodel object bound to the vamsas document object\r
+   */\r
+  protected Object getvObj2jv(org.vamsas.client.Vobject vobj) {\r
+    VorbaId id = vobj.getVorbaId();\r
+    if (id == null)\r
+    {\r
+      id = cdoc.registerObject(vobj);\r
+      Cache.log\r
+      .debug("Registering new object and returning null for getvObj2jv");\r
+      return null;\r
+    }\r
+    if (vobj2jv.containsKey(vobj.getVorbaId()))\r
+      return vobj2jv.get(vobj.getVorbaId());\r
+    return null;\r
+  }\r
+\r
+  protected void bindjvvobj(Object jvobj, org.vamsas.client.Vobject vobj) {\r
+    VorbaId id = vobj.getVorbaId();\r
+    if (id == null)\r
+    {\r
+      id = cdoc.registerObject(vobj);\r
+      if (id==null || vobj.getVorbaId()==null)\r
+        Cache.log.error("Failed to get id for "+(vobj.isRegisterable() ? "registerable" : "unregisterable") +" object "+vobj);\r
+    }\r
+    \r
+    if (vobj2jv.containsKey(vobj.getVorbaId()) && !((VorbaId)vobj2jv.get(vobj.getVorbaId())).equals(jvobj)) {\r
+      Cache.log.debug("Warning? Overwriting existing vamsas id binding for "+vobj.getVorbaId(), new Exception("Overwriting vamsas id binding."));\r
+    }\r
+    else if (jv2vobj.containsKey(jvobj) && !((VorbaId)jv2vobj.get(jvobj)).equals(vobj.getVorbaId())) \r
+    {\r
+      Cache.log.debug("Warning? Overwriting existing jalview object binding for "+jvobj, new Exception("Overwriting jalview object binding."));\r
+    }\r
+    /* 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"));\r
+    }*/\r
+    // we just update the hash's regardless!\r
+    vobj2jv.put(vobj.getVorbaId(), jvobj);\r
+    // JBPNote - better implementing a hybrid invertible hash.\r
+    jv2vobj.put(jvobj, vobj.getVorbaId());   \r
+  }\r
+\r
+  /**\r
+   * put the alignment viewed by AlignViewport into cdoc.\r
+   * \r
+   * @param av alignViewport to be stored\r
+   * @param aFtitle title for alignment\r
+   */\r
+  public void storeVAMSAS(AlignViewport av, String aFtitle) {\r
+    try\r
+    {\r
+      jalview.datamodel.AlignmentI jal = av.getAlignment();\r
+      boolean nw = false;\r
+      VAMSAS root = null; // will be resolved based on Dataset Parent.\r
+      // /////////////////////////////////////////\r
+      // SAVE THE DATASET\r
+      if (jal.getDataset() == null)\r
+      {\r
+        Cache.log.warn("Creating new dataset for an alignment.");\r
+        jal.setDataset(null);\r
+      }\r
+      DataSet dataset = (DataSet) getjv2vObj(jal.getDataset());\r
+      if (dataset == null)\r
+      {\r
+        root = cdoc.getVamsasRoots()[0]; // default vamsas root for modifying.\r
+        dataset = new DataSet();\r
+        root.addDataSet(dataset);\r
+        bindjvvobj(jal.getDataset(), dataset);\r
+        dataset.setProvenance(dummyProvenance());\r
+        dataset.getProvenance().addEntry(provEntry);\r
+        nw = true;\r
+      }\r
+      else\r
+      {\r
+        root = (VAMSAS) dataset.getV_parent();\r
+      }\r
+      // update dataset\r
+      Sequence sequence;\r
+      DbRef dbref;\r
+      // set new dataset and alignment sequences based on alignment Nucleotide\r
+      // flag.\r
+      // this *will* break when alignment contains both nucleotide and amino\r
+      // acid sequences.\r
+      String dict = jal.isNucleotide() ? org.vamsas.objects.utils.SymbolDictionary.STANDARD_NA\r
+          : org.vamsas.objects.utils.SymbolDictionary.STANDARD_AA;\r
+      for (int i = 0; i < jal.getHeight(); i++)\r
+      {\r
+        SequenceI sq = jal.getSequenceAt(i).getDatasetSequence(); // only insert\r
+        // referenced\r
+        // sequences\r
+        // to dataset.\r
+        sequence = (Sequence) getjv2vObj(sq);\r
+        if (sequence == null)\r
+        {\r
+          sequence = new Sequence();\r
+          bindjvvobj(sq, sequence);\r
+          sq.setVamsasId(sequence.getVorbaId().getId());\r
+          sequence.setSequence(sq.getSequence());\r
+          sequence.setDictionary(dict);\r
+          sequence.setName(jal.getDataset().getSequenceAt(i).getName());\r
+          sequence.setStart(jal.getDataset().getSequenceAt(i).getStart());\r
+          sequence.setEnd(jal.getDataset().getSequenceAt(i).getEnd());\r
+          dataset.addSequence(sequence);\r
+        }\r
+        else\r
+        {\r
+          // verify principal attributes. and update any new\r
+          // features/references.\r
+          System.out.println("update dataset sequence object.");\r
+        }\r
+        if (sq.getSequenceFeatures() != null)\r
+        {\r
+          int sfSize = sq.getSequenceFeatures().length;\r
+\r
+          for (int sf = 0; sf < sfSize; sf++)\r
+          {\r
+            jalview.datamodel.SequenceFeature feature = (jalview.datamodel.SequenceFeature) sq\r
+            .getSequenceFeatures()[sf];\r
+\r
+            DataSetAnnotations dsa = (DataSetAnnotations) getjv2vObj(feature);\r
+            if (dsa == null)\r
+            {\r
+              dsa = (DataSetAnnotations) getDSAnnotationFromJalview(\r
+                  new DataSetAnnotations(), feature);\r
+              if (dsa.getProvenance() == null)\r
+              {\r
+                dsa.setProvenance(new Provenance());\r
+              }\r
+              addProvenance(dsa.getProvenance(), "created"); // JBPNote - need\r
+              // to update\r
+              dsa.setSeqRef(sequence);\r
+              bindjvvobj(feature, dsa);\r
+              dataset.addDataSetAnnotations(dsa);\r
+            }\r
+            else\r
+            {\r
+              // todo: verify and update dataset annotations for sequence\r
+              System.out.println("update dataset sequence annotations.");\r
+            }\r
+          }\r
+        }\r
+\r
+        if (sq.getDBRef() != null)\r
+        {\r
+          DBRefEntry[] entries = sq.getDBRef();\r
+          jalview.datamodel.DBRefEntry dbentry;\r
+          for (int db = 0; db < entries.length; db++)\r
+          {\r
+            dbentry = entries[db];\r
+            dbref = (DbRef) getjv2vObj(dbentry);\r
+            if (dbref == null)\r
+            {\r
+              dbref = new DbRef();\r
+              bindjvvobj(dbentry, dbref);\r
+              dbref.setAccessionId(dbentry.getAccessionId());\r
+              dbref.setSource(dbentry.getSource());\r
+              dbref.setVersion(dbentry.getVersion());\r
+              /*\r
+               * TODO: Maps are not yet supported by Jalview. Map vMap = new\r
+               * Map(); vMap.set dbref.addMap(vMap);\r
+               */\r
+              sequence.addDbRef(dbref);\r
+            }\r
+            else\r
+            {\r
+              // TODO: verify and update dbrefs in vamsas document\r
+              // there will be trouble when a dataset sequence is modified to\r
+              // contain more residues than were originally referenced - we must\r
+              // then make a number of dataset sequence entries\r
+              System.out\r
+              .println("update dataset sequence database references.");\r
+            }\r
+          }\r
+\r
+        }\r
+      }\r
+      // dataset.setProvenance(getVamsasProvenance(jal.getDataset().getProvenance()));\r
+      // ////////////////////////////////////////////\r
+\r
+      // ////////////////////////////////////////////\r
+      // Save the Alignments\r
+\r
+      Alignment alignment = (Alignment) getjv2vObj(av); // this is so we can get the alignviewport back \r
+      if (alignment == null)\r
+      {\r
+        alignment = new Alignment();\r
+        bindjvvobj(av, alignment);\r
+        if (alignment.getProvenance() == null)\r
+          alignment.setProvenance(new Provenance());\r
+        addProvenance(alignment.getProvenance(), "added"); // TODO: insert some\r
+        // sensible source\r
+        // here\r
+        dataset.addAlignment(alignment);\r
+        {\r
+          Property title = new Property();\r
+          title.setName("jalview:AlTitle");\r
+          title.setType("string");\r
+          title.setContent(aFtitle);\r
+          alignment.addProperty(title);\r
+        }\r
+        alignment.setGapChar(String.valueOf(av.getGapCharacter()));\r
+        AlignmentSequence alseq = null;\r
+        for (int i = 0; i < jal.getHeight(); i++)\r
+        {\r
+          alseq = new AlignmentSequence();\r
+          // TODO: VAMSAS: translate lowercase symbols to annotation ?\r
+          alseq.setSequence(jal.getSequenceAt(i).getSequence());\r
+          alseq.setName(jal.getSequenceAt(i).getName());\r
+          alseq.setStart(jal.getSequenceAt(i).getStart());\r
+          alseq.setEnd(jal.getSequenceAt(i).getEnd());\r
+          alseq.setRefid(getjv2vObj(jal.getSequenceAt(i).getDatasetSequence()));\r
+          alignment.addAlignmentSequence(alseq);\r
+          bindjvvobj(jal.getSequenceAt(i), alseq);\r
+        }\r
+      }\r
+      else\r
+      {\r
+        // todo: verify and update mutable alignment props.\r
+        if (alignment.getModifiable())\r
+        {\r
+          System.out.println("update alignment in document.");\r
+        }\r
+        else\r
+        {\r
+          System.out\r
+          .println("update edited alignment to new alignment in document.");\r
+        }\r
+      }\r
+      // ////////////////////////////////////////////\r
+      // SAVE Alignment Sequence Features\r
+      for (int i = 0, iSize = alignment.getAlignmentSequenceCount(); i < iSize; i++)\r
+      {\r
+        AlignmentSequence valseq;\r
+        SequenceI alseq = (SequenceI) getvObj2jv(valseq = alignment\r
+            .getAlignmentSequence(i));\r
+        if (alseq != null && alseq.getSequenceFeatures() != null)\r
+        {\r
+          jalview.datamodel.SequenceFeature[] features = alseq\r
+          .getSequenceFeatures();\r
+          for (int f = 0; f < features.length; f++)\r
+          {\r
+            if (features[f] != null)\r
+            {\r
+              AlignmentSequenceAnnotation valseqf = (AlignmentSequenceAnnotation) getjv2vObj(features[i]);\r
+              if (valseqf == null)\r
+              {\r
+\r
+                valseqf = (AlignmentSequenceAnnotation) getDSAnnotationFromJalview(\r
+                    new AlignmentSequenceAnnotation(), features[i]);\r
+                if (valseqf.getProvenance() == null)\r
+                {\r
+                  valseqf.setProvenance(new Provenance());\r
+                }\r
+                addProvenance(valseqf.getProvenance(), "created"); // JBPNote -\r
+                // need to\r
+                // update\r
+                bindjvvobj(features[i], valseqf);\r
+                valseq.addAlignmentSequenceAnnotation(valseqf);\r
+              }\r
+            }\r
+\r
+          }\r
+        }\r
+      }\r
+\r
+      // ////////////////////////////////////////////\r
+      // SAVE ANNOTATIONS\r
+      if (jal.getAlignmentAnnotation() != null)\r
+      {\r
+        jalview.datamodel.AlignmentAnnotation[] aa = jal\r
+        .getAlignmentAnnotation();\r
+        java.util.HashMap AlSeqMaps = new HashMap(); // stores int maps from\r
+        // alignment columns to\r
+        // sequence positions.\r
+        for (int i = 0; i < aa.length; i++)\r
+        {\r
+          if (aa[i] == null || isJalviewOnly(aa[i]))\r
+          {\r
+            continue;\r
+          }\r
+          if (aa[i].sequenceRef != null)\r
+          {\r
+            org.vamsas.objects.core.AlignmentSequence alsref = (org.vamsas.objects.core.AlignmentSequence) getjv2vObj(aa[i].sequenceRef);\r
+            org.vamsas.objects.core.AlignmentSequenceAnnotation an = (org.vamsas.objects.core.AlignmentSequenceAnnotation) getjv2vObj(aa[i]);\r
+            int[] gapMap = null;\r
+            if (AlSeqMaps.containsKey(aa[i].sequenceRef))\r
+            {\r
+              gapMap = (int[]) AlSeqMaps.get(aa[i].sequenceRef);\r
+            }\r
+            else\r
+            {\r
+              gapMap = new int[aa[i].sequenceRef.getLength()];\r
+              // map from alignment position to sequence position.\r
+              int[] sgapMap = aa[i].sequenceRef.gapMap();\r
+              for (int a = 0; a < sgapMap.length; a++)\r
+                gapMap[sgapMap[a]] = a;\r
+            }\r
+            if (an == null)\r
+            {\r
+              an = new org.vamsas.objects.core.AlignmentSequenceAnnotation();\r
+              Seg vSeg = new Seg();\r
+              vSeg.setStart(1);\r
+              vSeg.setInclusive(true);\r
+              vSeg.setEnd(gapMap.length);\r
+              an.addSeg(vSeg);\r
+              an.setType("jalview:SecondaryStructurePrediction");// TODO: better fix this rough guess ;)\r
+              alsref.addAlignmentSequenceAnnotation(an);\r
+              bindjvvobj(aa[i],an);\r
+              // LATER: much of this is verbatim from the alignmentAnnotation\r
+              // method below. suggests refactoring to make rangeAnnotation the\r
+              // base class\r
+              an.setDescription(aa[i].description);\r
+              if (aa[i].graph > 0)\r
+                an.setGraph(true); // aa[i].graph);\r
+              else\r
+                an.setGraph(false);\r
+              an.setLabel(aa[i].label);\r
+              an.setProvenance(dummyProvenance()); // get provenance as user\r
+              // created, or jnet, or\r
+              // something else.\r
+              an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote -\r
+              // originally we\r
+              // were going to\r
+              // store\r
+              // graphGroup in\r
+              // the Jalview\r
+              // specific\r
+              // bits.\r
+              AnnotationElement ae;\r
+              for (int a = 0; a < aa[i].annotations.length; a++)\r
+              {\r
+                if (aa[i].annotations[a] == null)\r
+                {\r
+                  continue;\r
+                }\r
+\r
+                ae = new AnnotationElement();\r
+                ae.setDescription(aa[i].annotations[a].description);\r
+                ae.addGlyph(new Glyph());\r
+                ae.getGlyph(0)\r
+                .setContent(aa[i].annotations[a].displayCharacter); // assume\r
+                // jax-b\r
+                // takes\r
+                // care\r
+                // of\r
+                // utf8\r
+                // translation\r
+                if (aa[i].graph!=jalview.datamodel.AlignmentAnnotation.NO_GRAPH)\r
+                  ae.addValue(aa[i].annotations[a].value);\r
+                ae.setPosition(gapMap[a]+1); // position w.r.t. AlignmentSequence\r
+                // symbols\r
+                if (aa[i].annotations[a].secondaryStructure != ' ')\r
+                {\r
+                  // we only write an annotation where it really exists.\r
+                  Glyph ss = new Glyph();\r
+                  ss\r
+                  .setDict(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);\r
+                  ss.setContent(String\r
+                      .valueOf(aa[i].annotations[a].secondaryStructure));\r
+                  ae.addGlyph(ss);\r
+                }\r
+                an.addAnnotationElement(ae);\r
+              }\r
+            }\r
+            else\r
+            {\r
+              // update reference sequence Annotation\r
+              if (an.getModifiable())\r
+              {\r
+                // verify existing alignment sequence annotation is up to date\r
+                System.out.println("update alignment sequence annotation.");\r
+              }\r
+              else\r
+              {\r
+                // verify existing alignment sequence annotation is up to date\r
+                System.out\r
+                .println("make new alignment sequence annotation if modification has happened.");\r
+              }\r
+            }\r
+          }\r
+          else\r
+          {\r
+            // add Alignment Annotation\r
+            org.vamsas.objects.core.AlignmentAnnotation an = (org.vamsas.objects.core.AlignmentAnnotation) getjv2vObj(aa[i]);\r
+            if (an == null)\r
+            {\r
+              an = new org.vamsas.objects.core.AlignmentAnnotation();\r
+              an.setType("jalview:AnnotationRow");\r
+              an.setDescription(aa[i].description);\r
+              alignment.addAlignmentAnnotation(an);\r
+              Seg vSeg = new Seg();\r
+              vSeg.setStart(1);\r
+              vSeg.setInclusive(true);\r
+              vSeg.setEnd(jal.getWidth());\r
+              an.addSeg(vSeg);\r
+              if (aa[i].graph > 0)\r
+                an.setGraph(true); // aa[i].graph);\r
+              an.setLabel(aa[i].label);\r
+              an.setProvenance(dummyProvenance());\r
+              if (aa[i].graph!=aa[i].NO_GRAPH) {\r
+                an.setGroup(Integer.toString(aa[i].graphGroup)); // // JBPNote -\r
+                // originally we\r
+              // were going to\r
+              // store\r
+              // graphGroup in\r
+              // the Jalview\r
+              // specific\r
+              // bits.\r
+                an.setGraph(true);\r
+              } else {\r
+                an.setGraph(false);\r
+              }\r
+              AnnotationElement ae;\r
+\r
+              for (int a = 0; a < aa[i].annotations.length; a++)\r
+              {\r
+                if ((aa[i] == null) || (aa[i].annotations[a] == null))\r
+                {\r
+                  continue;\r
+                }\r
+\r
+                ae = new AnnotationElement();\r
+                ae.setDescription(aa[i].annotations[a].description);\r
+                ae.addGlyph(new Glyph());\r
+                ae.getGlyph(0)\r
+                .setContent(aa[i].annotations[a].displayCharacter); // assume\r
+                // jax-b\r
+                // takes\r
+                // care\r
+                // of\r
+                // utf8\r
+                // translation\r
+                ae.addValue(aa[i].annotations[a].value);\r
+                ae.setPosition(a+1);\r
+                if (aa[i].annotations[a].secondaryStructure != ' ')\r
+                {\r
+                  Glyph ss = new Glyph();\r
+                  ss\r
+                  .setDict(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE);\r
+                  ss.setContent(String\r
+                      .valueOf(aa[i].annotations[a].secondaryStructure));\r
+                  ae.addGlyph(ss);\r
+                }\r
+                an.addAnnotationElement(ae);\r
+              }\r
+              if (aa[i].editable) {\r
+                //an.addProperty(newProperty("jalview:editable", null, "true"));\r
+                an.setModifiable(true);\r
+              }\r
+              if (aa[i].graph!=jalview.datamodel.AlignmentAnnotation.NO_GRAPH) {\r
+                an.setGraph(true);\r
+                an.setGroup(Integer.toString(aa[i].graphGroup));\r
+                an.addProperty(newProperty("jalview:graphType",null,\r
+                    ((aa[i].graph==jalview.datamodel.AlignmentAnnotation.BAR_GRAPH) ? "BAR_GRAPH" : "LINE_GRAPH")));\r
+\r
+                /** and on and on.. \r
+                 vProperty=new Property();\r
+                  vProperty.setName("jalview:graphThreshhold");\r
+                  vProperty.setContent(aa[i].threshold);\r
+                 */\r
+\r
+              }\r
+            }\r
+            else\r
+            {\r
+              if (an.getModifiable())\r
+              {\r
+                // verify annotation - update (perhaps)\r
+                Cache.log.info("update alignment sequence annotation. not yet implemented.");\r
+              }\r
+              else\r
+              {\r
+                // verify annotation - update (perhaps)\r
+                Cache.log.info("updated alignment sequence annotation added.");\r
+              }\r
+            }\r
+          }\r
+        }\r
+      }\r
+      // /////////////////////////////////////////////////////\r
+\r
+      // //////////////////////////////////////////////\r
+      // /SAVE THE TREES\r
+      // /////////////////////////////////\r
+      // FIND ANY ASSOCIATED TREES\r
+      if (Desktop.desktop != null)\r
+      {\r
+        javax.swing.JInternalFrame[] frames = Desktop.desktop.getAllFrames();\r
+\r
+        for (int t = 0; t < frames.length; t++)\r
+        {\r
+          if (frames[t] instanceof TreePanel)\r
+          {\r
+            TreePanel tp = (TreePanel) frames[t];\r
+\r
+            if (tp.getAlignment() == jal)\r
+            {\r
+              Tree tree = (Tree) getjv2vObj(tp);\r
+              if (tree == null)\r
+              {\r
+                tree = new Tree();\r
+                bindjvvobj(tp, tree);\r
+                tree.setTitle(tp.getTitle());\r
+                Newick newick = new Newick();\r
+                // TODO: translate sequenceI to leaf mappings to vamsas\r
+                // references - see tree specification in schema.\r
+                newick.setContent(tp.getTree().toString());\r
+                newick.setTitle(tp.getTitle());\r
+                tree.addNewick(newick);\r
+                tree.setProvenance(makeTreeProvenance(jal, tp));\r
+                alignment.addTree(tree);\r
+              }\r
+              else\r
+              {\r
+                if (tree.getModifiable())\r
+                {\r
+                  // verify any changes.\r
+                  System.out.println("Update tree in document.");\r
+                }\r
+                else\r
+                {\r
+                  System.out\r
+                  .println("Add modified tree as new tree in document.");\r
+                }\r
+              }\r
+            }\r
+          }\r
+        }\r
+      }\r
+      // Store Jalview specific stuff in the Jalview appData\r
+      // not implemented in the SimpleDoc interface.\r
+    }\r
+\r
+    catch (Exception ex)\r
+    {\r
+      ex.printStackTrace();\r
+    }\r
+\r
+  }\r
+\r
+  private Property newProperty(String name, String type, String content) {\r
+    Property vProperty=new Property();\r
+    vProperty.setName(name);\r
+    if (type!=null)\r
+      vProperty.setType(type);\r
+    else\r
+      vProperty.setType("String");\r
+    vProperty.setContent(content);\r
+    return vProperty;\r
+  }\r
+\r
+  /**\r
+   * correctly create a RangeAnnotation from a jalview sequence feature\r
+   * \r
+   * @param dsa\r
+   *          (typically DataSetAnnotations or AlignmentSequenceAnnotation)\r
+   * @param feature\r
+   *          (the feature to be mapped from)\r
+   * @return\r
+   */\r
+  private RangeAnnotation getDSAnnotationFromJalview(RangeAnnotation dsa,\r
+      SequenceFeature feature) {\r
+    dsa.setType(feature.getType());\r
+    Seg vSeg = new Seg();\r
+    vSeg.setStart(feature.getBegin());\r
+    vSeg.setEnd(feature.getEnd());\r
+    vSeg.setInclusive(true);\r
+    dsa.addSeg(vSeg);\r
+    dsa.setDescription(feature.getDescription());\r
+    dsa.setStatus(feature.getStatus());\r
+    if (feature.links != null && feature.links.size() > 0)\r
+    {\r
+      for (int i = 0, iSize = feature.links.size(); i < iSize; i++)\r
+      {\r
+        String link = (String) feature.links.elementAt(i);\r
+        int sep = link.indexOf('|');\r
+        if (sep > -1)\r
+        {\r
+          Link vLink = new Link();\r
+          if (sep > 0)\r
+            vLink.setContent(link.substring(0, sep - 1));\r
+          else\r
+            vLink.setContent("");\r
+          vLink.setHref(link.substring(sep + 1)); // TODO: validate href.\r
+          dsa.addLink(vLink);\r
+        }\r
+      }\r
+    }\r
+    dsa.setGroup(feature.getFeatureGroup());\r
+    return dsa;\r
+  }\r
+\r
+  /**\r
+   * correctly creates provenance for trees calculated on an alignment by\r
+   * jalview.\r
+   * \r
+   * @param jal\r
+   * @param tp\r
+   * @return\r
+   */\r
+  private Provenance makeTreeProvenance(AlignmentI jal, TreePanel tp) {\r
+    Provenance prov = new Provenance();\r
+    prov.addEntry(new Entry());\r
+    prov.getEntry(0).setAction("imported "+tp.getTitle());\r
+    prov.getEntry(0).setUser(provEntry.getUser());\r
+    prov.getEntry(0).setApp(provEntry.getApp());\r
+    prov.getEntry(0).setDate(provEntry.getDate());\r
+    if (tp.getTree().hasOriginalSequenceData())\r
+    {\r
+      Input vInput = new Input();\r
+      // LATER: check to see if tree input data is contained in this alignment -\r
+      // or just correctly resolve the tree's seqData to the correct alignment in\r
+      // the document.\r
+      // vInput.setObjRef(getjv2vObj(jal));\r
+      vInput.setObjRef(getjv2vObj(tp.getViewPort()));\r
+      prov.getEntry(0).setAction("created "+tp.getTitle());\r
+      prov.getEntry(0).addInput(vInput);\r
+      vInput.setName("jalview:seqdist");\r
+      prov.getEntry(0).addParam(new Param());\r
+      prov.getEntry(0).getParam(0).setName("treeType");\r
+      prov.getEntry(0).getParam(0).setType("utf8");\r
+      prov.getEntry(0).getParam(0).setContent("NJ");\r
+      \r
+      int ranges[] = tp.getTree().seqData.getVisibleContigs();\r
+      // VisibleContigs are with respect to alignment coordinates. Still need offsets\r
+      int start= tp.getTree().seqData.getAlignmentOrigin();\r
+      for (int r = 0; r < ranges.length; r += 2)\r
+      {\r
+        Seg visSeg = new Seg();\r
+        visSeg.setStart(1+start+ranges[r]);\r
+        visSeg.setEnd(start+ranges[r + 1]);\r
+        visSeg.setInclusive(true);\r
+        vInput.addSeg(visSeg);\r
+      }\r
+    }\r
+    return prov;\r
+  }\r
+\r
+  /**\r
+   * \r
+   * @param tp\r
+   * @return Object[] { AlignmentView, AlignmentI - reference alignment for\r
+   *         input }\r
+   */\r
+  private Object[] recoverInputData(Provenance tp) {\r
+    for (int pe = 0; pe < tp.getEntryCount(); pe++)\r
+    {\r
+      if (tp.getEntry(pe).getInputCount() > 0)\r
+      {\r
+        if (tp.getEntry(pe).getInputCount() > 1)\r
+          Cache.log.warn("Ignoring additional input spec in provenance entry "\r
+              + tp.getEntry(pe).toString());\r
+        // LATER: deal sensibly with multiple inputs.\r
+        Input vInput = tp.getEntry(pe).getInput(0);\r
+        if (vInput.getObjRef() instanceof org.vamsas.objects.core.Alignment)\r
+        {\r
+          // recover an AlignmentView for the input data\r
+          AlignViewport javport = (AlignViewport) getvObj2jv((org.vamsas.client.Vobject) vInput\r
+              .getObjRef());\r
+          jalview.datamodel.AlignmentI jal = javport.getAlignment();\r
+          jalview.datamodel.CigarArray view = javport.getAlignment().getCompactAlignment();\r
+          int from = 1, to = jal.getWidth();\r
+          int offset=0; // deleteRange modifies its frame of reference\r
+          for (int r = 0, s = vInput.getSegCount(); r < s; r++)\r
+          {\r
+            Seg visSeg = vInput.getSeg(r);\r
+            int se[] = getSegRange(visSeg,true); // jalview doesn't do bidirection alignments yet.\r
+            if (to < se[1])\r
+              Cache.log.warn("Ignoring invalid segment in InputData spec.");\r
+            else\r
+            {\r
+              if (se[0] > from)\r
+              {\r
+                view.deleteRange(offset+from-1, offset+se[0] - 2);\r
+                offset-=se[0]-from;\r
+              }\r
+              from = se[1] + 1;\r
+            }\r
+          }\r
+          if (from < to)\r
+          {\r
+            view.deleteRange(offset+from-1, offset+to-1); // final deletion - TODO: check off by\r
+            // one for to\r
+          }\r
+          return new Object[] { new AlignmentView(view), jal };\r
+        }\r
+      }\r
+    }\r
+    Cache.log.debug("Returning null for input data recovery from provenance.");\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * get start<end range of segment, adjusting for inclusivity flag and\r
+   * polarity.\r
+   *  \r
+   * @param visSeg\r
+   * @param ensureDirection when true - always ensure start is less than end.\r
+   * @return int[] { start, end, direction} where direction==1 for range running from end to start.\r
+   */\r
+  private int[] getSegRange(Seg visSeg, boolean ensureDirection) {\r
+    boolean incl = visSeg.getInclusive();\r
+    // adjust for inclusive flag.\r
+    int pol = (visSeg.getStart() <= visSeg.getEnd()) ? 1 : -1; // polarity of\r
+    // region.\r
+    int start = visSeg.getStart() + (incl ? 0 : pol);\r
+    int end = visSeg.getEnd() + (incl ? 0 : -pol);\r
+    if (ensureDirection && pol==-1)\r
+    {\r
+      // jalview doesn't deal with inverted ranges, yet.\r
+      int t = end;\r
+      end = start;\r
+      start = t;\r
+    }\r
+    return new int[] { start, end, pol<0 ? 1 : 0 };\r
+  }\r
+\r
+  /**\r
+   * \r
+   * @param annotation\r
+   * @return true if annotation is not to be stored in document\r
+   */\r
+  private boolean isJalviewOnly(AlignmentAnnotation annotation) {\r
+    return annotation.label.equals("Quality")\r
+    || annotation.label.equals("Conservation")\r
+    || annotation.label.equals("Consensus");\r
+  }\r
+  /**\r
+   * This will return the first AlignFrame viewing AlignViewport av.\r
+   * It will break if there are more than one AlignFrames viewing a particular av.\r
+   * This also shouldn't be in the io package.\r
+   * @param av\r
+   * @return alignFrame for av\r
+   */\r
+  public AlignFrame getAlignFrameFor(AlignViewport av) {\r
+    if (Desktop.desktop != null)\r
+    {\r
+      javax.swing.JInternalFrame[] frames = Desktop.desktop.getAllFrames();\r
+\r
+      for (int t = 0; t < frames.length; t++)\r
+      {\r
+        if (frames[t] instanceof AlignFrame) {\r
+          if (((AlignFrame) frames[t]).getViewport()==av)\r
+            return (AlignFrame) frames[t];\r
+        }\r
+      }\r
+    }\r
+    return null;\r
+  }\r
+  public void updateToJalview() {\r
+    VAMSAS _roots[] = cdoc.getVamsasRoots();\r
+\r
+    for (int _root = 0; _root<_roots.length; _root++) {\r
+      VAMSAS root = _roots[_root];\r
+      boolean newds=false;\r
+      for (int _ds=0,_nds=root.getDataSetCount(); _ds<_nds; _ds++) {\r
+        // ///////////////////////////////////\r
+        // ///LOAD DATASET\r
+        DataSet dataset = root.getDataSet(_ds);\r
+        int i, iSize = dataset.getSequenceCount();\r
+        Vector dsseqs;\r
+        jalview.datamodel.Alignment jdataset = (jalview.datamodel.Alignment) getvObj2jv(dataset);\r
+        int jremain=0;\r
+        if (jdataset==null) {\r
+          Cache.log.debug("Initialising new jalview dataset fields");\r
+          newds=true;\r
+          dsseqs=new Vector();\r
+        } else {\r
+          Cache.log.debug("Update jalview dataset from vamsas.");\r
+          jremain=jdataset.getHeight();\r
+          dsseqs=jdataset.getSequences();\r
+        }\r
+\r
+        // TODO: test sequence merging - we preserve existing non vamsas\r
+        // sequences but add in any new vamsas ones, and don't yet update any\r
+        // sequence attributes\r
+        for (i = 0; i < iSize ; i++)\r
+        {\r
+          Sequence vdseq = dataset.getSequence(i);\r
+          jalview.datamodel.SequenceI dsseq = (SequenceI) getvObj2jv(vdseq);\r
+          if (dsseq!=null) {\r
+            if (!dsseq.getSequence().equals(vdseq.getSequence()))\r
+              throw new Error("Broken! - mismatch of dataset sequence and jalview internal dataset sequence.");\r
+            jremain--;\r
+          } else {\r
+            dsseq = new jalview.datamodel.Sequence(\r
+                dataset.getSequence(i).getName(),\r
+                dataset.getSequence(i).getSequence(),\r
+                dataset.getSequence(i).getStart(),\r
+                dataset.getSequence(i).getEnd()  );\r
+            bindjvvobj(dsseq, dataset.getSequence(i));\r
+            dsseq.setVamsasId(dataset.getSequence(i).getVorbaId().getId());\r
+            dsseqs.add(dsseq);\r
+          }\r
+          if (vdseq.getDbRefCount()>0) {\r
+            DbRef [] dbref = vdseq.getDbRef();\r
+            for(int db=0; db<dbref.length; db++)\r
+            {\r
+              jalview.datamodel.DBRefEntry dbr=(jalview.datamodel.DBRefEntry) getvObj2jv(dbref[db]);\r
+              if (dbr==null) {\r
+                // add new dbref\r
+                dsseq.addDBRef(dbr= new jalview.datamodel.DBRefEntry\r
+                    (\r
+                        dbref[db].getSource().toString(),\r
+                        dbref[db].getVersion().toString(),\r
+                        dbref[db].getAccessionId().toString()));\r
+                bindjvvobj(dbr, dbref[db]);\r
+              }\r
+            }\r
+          }\r
+        }\r
+\r
+        if (newds) {\r
+          SequenceI[] seqs = new SequenceI[dsseqs.size()];\r
+          for (i=0,iSize=dsseqs.size(); i<iSize; i++) {\r
+            seqs[i]=(SequenceI) dsseqs.elementAt(i);\r
+            dsseqs.setElementAt(null, i);\r
+          }\r
+          jdataset = new jalview.datamodel.Alignment(seqs);\r
+          Cache.log.debug("New vamsas dataset imported into jalview.");\r
+          bindjvvobj(jdataset, dataset);\r
+        }\r
+        // ////////\r
+        // add any new dataset sequence feature annotations\r
+        if (dataset.getDataSetAnnotations() != null) {\r
+          for (int dsa = 0; dsa < dataset.getDataSetAnnotationsCount(); dsa++) {\r
+            DataSetAnnotations dseta=dataset.getDataSetAnnotations(dsa);\r
+            SequenceI dsSeq=(SequenceI) getvObj2jv((Vobject) dseta.getSeqRef());\r
+            if (dsSeq==null) {\r
+              jalview.bin.Cache.log.warn("Couldn't resolve jalview sequenceI for dataset object reference "+((Vobject)dataset.getDataSetAnnotations(dsa).getSeqRef()).getVorbaId().getId());\r
+            } else {\r
+              if (dseta.getAnnotationElementCount()==0) {\r
+                jalview.datamodel.SequenceFeature sf=(jalview.datamodel.SequenceFeature) getvObj2jv(dseta);\r
+                if (sf==null) {\r
+                  dsSeq.addSequenceFeature(sf=getJalviewSeqFeature(dseta));\r
+                  bindjvvobj(sf, dseta);\r
+                }\r
+              } else {\r
+                // TODO: deal with alignmentAnnotation style annotation\r
+                // appearing on dataset sequences.\r
+                // JBPNote: we could just add them to all alignments but\r
+                // that may complicate cross references in the jalview\r
+                // datamodel\r
+                Cache.log.warn("Ignoring dataset annotation with annotationElements. Not yet supported in jalview.");\r
+              }\r
+            }\r
+          }\r
+        }\r
+\r
+        if (dataset.getAlignmentCount()>0) {\r
+          // LOAD ALIGNMENTS from DATASET \r
+\r
+          for (int al=0,nal=dataset.getAlignmentCount(); al<nal; al++) {\r
+            org.vamsas.objects.core.Alignment alignment = dataset.getAlignment(al);\r
+            AlignViewport av = (AlignViewport) getvObj2jv(alignment);\r
+            jalview.datamodel.AlignmentI jal=null;\r
+            if (av!=null)\r
+              jal = av.getAlignment(); \r
+            iSize = alignment.getAlignmentSequenceCount();\r
+            boolean newal=(jal==null) ? true : false;\r
+            Vector newasAnnots=new Vector();\r
+            char gapChar=' '; // default for new alignments read in from the document\r
+            if (jal!=null) {\r
+              dsseqs=jal.getSequences(); // for merge/update\r
+              gapChar=jal.getGapCharacter();\r
+            } else {\r
+              dsseqs=new Vector();\r
+            }\r
+            char valGapchar=alignment.getGapChar().charAt(0);\r
+            for (i = 0; i < iSize; i++)\r
+            {\r
+              AlignmentSequence valseq = alignment.getAlignmentSequence(i);\r
+              jalview.datamodel.SequenceI alseq = (SequenceI) getvObj2jv(valseq);\r
+              if (alseq!=null) {\r
+                //TODO: upperCase/LowerCase situation here ? do we allow it ?\r
+                //if (!alseq.getSequence().equals(valseq.getSequence())) {\r
+                // throw new Error("Broken! - mismatch of dataset sequence and jalview internal dataset sequence.");\r
+                if (Cache.log.isDebugEnabled())\r
+                  Cache.log.debug("Updating apparently edited sequence "+alseq.getName());\r
+                // this might go *horribly* wrong\r
+                alseq.setSequence(new String(valseq.getSequence()).replace(valGapchar, gapChar));\r
+                jremain--;\r
+              } else {\r
+                alseq = new jalview.datamodel.Sequence(\r
+                    valseq.getName(),\r
+                    valseq.getSequence().replace(valGapchar, gapChar),\r
+                    valseq.getStart(),\r
+                    valseq.getEnd()  );\r
+                \r
+                Vobject datsetseq = (Vobject)valseq.getRefid();\r
+                if (datsetseq!=null) {\r
+                  alseq.setDatasetSequence((SequenceI)getvObj2jv(datsetseq)); // exceptions if AlignemntSequence reference isn't a simple SequenceI\r
+                } else {\r
+                  Cache.log.error("Invalid dataset sequence id (null) for alignment sequence "+valseq.getVorbaId());\r
+                }\r
+                bindjvvobj(alseq, valseq);\r
+                alseq.setVamsasId(valseq.getVorbaId().getId());\r
+                dsseqs.add(alseq);\r
+              }\r
+              if (valseq.getAlignmentSequenceAnnotationCount()>0) {\r
+                AlignmentSequenceAnnotation[] vasannot=valseq.getAlignmentSequenceAnnotation();\r
+                for (int a=0; a<vasannot.length; a++) {\r
+                  jalview.datamodel.AlignmentAnnotation asa = (jalview.datamodel.AlignmentAnnotation) getvObj2jv(vasannot[a]); // TODO: 1:many jalview alignment sequence annotations\r
+                  if (asa==null) {\r
+                    int se[] = getBounds(vasannot[a]);\r
+                    asa = getjAlignmentAnnotation(jal, vasannot[a]);\r
+                    asa.sequenceRef=alseq;\r
+                    asa.createSequenceMapping(alseq, alseq.getStart()+se[0], false); // TODO: verify that positions in alseqAnnotation correspond to ungapped residue positions.\r
+                    bindjvvobj(asa, vasannot[a]);\r
+                    newasAnnots.add(asa);\r
+                  } else {\r
+                    // update existing annotation - can do this in place\r
+                    if (vasannot[a].getModifiable()) {\r
+                      Cache.log.info("UNIMPLEMENTED: not recovering user modifiable sequence alignment annotation");\r
+                      // TODO: should at least replace with new one - otherwise things will break\r
+                      // basically do this:\r
+                      // int se[] = getBounds(vasannot[a]);\r
+                      // asa.update(getjAlignmentAnnotation(jal, vasannot[a])); //  update from another annotation object in place.\r
+                      // asa.createSequenceMapping(alseq, se[0], false); \r
+\r
+                    }\r
+                  }\r
+                }\r
+              }\r
+            }\r
+            if (jal==null) {\r
+              SequenceI[] seqs = new SequenceI[dsseqs.size()];\r
+              for (i=0,iSize=dsseqs.size(); i<iSize; i++) {\r
+                seqs[i]=(SequenceI) dsseqs.elementAt(i);\r
+                dsseqs.setElementAt(null, i);\r
+              }\r
+              jal = new jalview.datamodel.Alignment(seqs);\r
+              Cache.log.debug("New vamsas alignment imported into jalview "+alignment.getVorbaId().getId());\r
+              jal.setDataset(jdataset);\r
+            }\r
+            if (newasAnnots!=null && newasAnnots.size()>0) {\r
+              // Add the new sequence annotations in to the alignment.\r
+              for (int an=0,anSize=newasAnnots.size(); an<anSize; an++) {\r
+                jal.addAnnotation((AlignmentAnnotation) newasAnnots.elementAt(an));\r
+                // TODO: check if anything has to be done - like calling adjustForAlignment or something.\r
+                newasAnnots.setElementAt(null, an);\r
+              }\r
+              newasAnnots=null;\r
+            }\r
+            // //////////////////////////////////////////\r
+            // //LOAD ANNOTATIONS FOR THE ALIGNMENT\r
+            // ////////////////////////////////////\r
+            if (alignment.getAlignmentAnnotationCount()>0)\r
+            {\r
+              org.vamsas.objects.core.AlignmentAnnotation[] an = alignment.getAlignmentAnnotation();\r
+\r
+              for (int j = 0; j < an.length; j++)\r
+              {\r
+                jalview.datamodel.AlignmentAnnotation jan=(jalview.datamodel.AlignmentAnnotation) getvObj2jv(an[j]);\r
+                if (jan!=null) {\r
+                  // update or stay the same.\r
+                  // TODO: should at least replace with a new one - otherwise things will break\r
+                  // basically do this:\r
+                  // jan.update(getjAlignmentAnnotation(jal, an[a])); //  update from another annotation object in place.\r
+\r
+                  Cache.log.debug("update from vamsas alignment annotation to existing jalview alignment annotation.");\r
+                  if (an[j].getModifiable()) {\r
+                    // TODO: user defined annotation is totally mutable... - so load it up or throw away if locally edited.\r
+                    Cache.log.info("NOT IMPLEMENTED - Recovering user-modifiable annotation - yet...");\r
+                  }\r
+                  // TODO: compare annotation element rows\r
+                  // TODO: compare props.\r
+                } else {\r
+                  jan = getjAlignmentAnnotation(jal, an[j]);\r
+                  jal.addAnnotation(jan);\r
+                  bindjvvobj(jan, an[j]);\r
+                }\r
+              }\r
+            }\r
+            AlignFrame alignFrame;\r
+            if (av==null) {\r
+              Cache.log.debug("New alignframe for alignment "+alignment.getVorbaId());\r
+              // ///////////////////////////////\r
+              // construct alignment view\r
+              alignFrame = new AlignFrame(jal, AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);\r
+              av=alignFrame.getViewport();\r
+              String title = alignment.getProvenance().getEntry(alignment.getProvenance().getEntryCount()-1).getAction();\r
+              if (alignment.getPropertyCount()>0) {\r
+                for (int p=0,pe=alignment.getPropertyCount(); p<pe; p++) {\r
+                  if (alignment.getProperty(p).getName().equals("jalview:AlTitle")) {\r
+                    title = alignment.getProperty(p).getContent();\r
+                  }\r
+                }\r
+              }\r
+              // TODO: automatically create meaningful title for a vamsas alignment using its provenance.\r
+              jalview.gui.Desktop.addInternalFrame(alignFrame, title + "("+alignment.getVorbaId()+")",\r
+                  AlignFrame.DEFAULT_WIDTH,\r
+                  AlignFrame.DEFAULT_HEIGHT);\r
+              bindjvvobj(av, alignment);\r
+            } else {\r
+              // find the alignFrame for jal.\r
+              // TODO: fix this so we retrieve the alignFrame handing av *directly*\r
+              alignFrame=getAlignFrameFor(av);\r
+            }\r
+            // LOAD TREES\r
+            // /////////////////////////////////////\r
+            if (alignment.getTreeCount() > 0)\r
+            {\r
+\r
+              for (int t = 0; t < alignment.getTreeCount(); t++)\r
+              {\r
+                Tree tree = alignment.getTree(t);\r
+                TreePanel tp=(TreePanel) getvObj2jv(tree);\r
+                if (tp!=null) {\r
+                  Cache.log.info("Update from vamsas document to alignment associated tree not implemented yet.");\r
+                } else {\r
+                  // make a new tree\r
+                  Object[] idata = this.recoverInputData(tree.getProvenance());\r
+                  try {\r
+                    AlignmentView inputData=null;\r
+                    if (idata!=null && idata[0]!=null)\r
+                      inputData = (AlignmentView) idata[0];\r
+                    tp = alignFrame.ShowNewickTree(\r
+                        new jalview.io.NewickFile(tree.getNewick(0).getContent()),\r
+                        tree.getNewick(0).getTitle()+" ("+tree.getVorbaId()+")",inputData,\r
+                        600, 500,\r
+                        t * 20 + 50, t * 20 + 50);\r
+                    bindjvvobj(tp, tree);\r
+                  } catch (Exception e) {\r
+                    Cache.log.warn("Problems parsing treefile '"+tree.getNewick(0).getContent()+"'",e);\r
+                  }\r
+                }\r
+              }\r
+            }\r
+\r
+          }\r
+        }\r
+      }\r
+    }\r
+  }\r
+  // bitfields - should be a template in j1.5\r
+  private static int HASSECSTR=0;\r
+  private static int HASVALS=1;\r
+  private static int HASHPHOB=2;\r
+  private static int HASDC=3;\r
+  private static int HASDESCSTR=4;\r
+  private static int HASTWOSTATE=5; // not used yet.\r
+  /**\r
+   * parses the AnnotationElements - if they exist - into jalview.datamodel.Annotation[] rows\r
+   * Two annotation rows are made if there are distinct annotation for both at 'pos' and 'after pos' at any particular site.\r
+   * @param annotation\r
+   * @return { boolean[static int constants ], int[ae.length] - map to annotated object frame, jalview.datamodel.Annotation[], jalview.datamodel.Annotation[] (after)}\r
+   */\r
+  private Object[] parseRangeAnnotation(org.vamsas.objects.core.RangeAnnotation annotation) {\r
+    // set these attributes by looking in the annotation to decide what kind of alignment annotation rows will be made\r
+    // TODO: potentially we might make several annotation rows from one vamsas alignment annotation. the jv2Vobj binding mechanism\r
+    // may not quite cope with this (without binding an array of annotations to a vamsas alignment annotation)\r
+    // summary flags saying what we found over the set of annotation rows.\r
+    boolean[] AeContent = new boolean[] { false, false, false, false, false};\r
+    int[] rangeMap = getMapping(annotation);\r
+    jalview.datamodel.Annotation[][] anot=new jalview.datamodel.Annotation[][] { \r
+        new jalview.datamodel.Annotation[rangeMap.length],\r
+        new jalview.datamodel.Annotation[rangeMap.length]\r
+    };\r
+    boolean mergeable=true; //false  if 'after positions cant be placed on same annotation row as positions. \r
+    \r
+    if (annotation.getAnnotationElementCount()>0) {\r
+      AnnotationElement ae[] = annotation.getAnnotationElement();\r
+      for (int aa = 0; aa < ae.length; aa++)\r
+      {\r
+        int pos = ae[aa].getPosition()-1;// pos counts from 1 to (|seg.start-seg.end|+1)\r
+        if (pos>=0 && pos<rangeMap.length) { \r
+          int row=ae[aa].getAfter()?1:0;\r
+          if (anot[row][pos]!=null) {\r
+            // only time this should happen is if the After flag is set.\r
+            Cache.log.debug("Ignoring duplicate annotation site at "+pos);\r
+            continue;\r
+          }\r
+          if (anot[1-row][pos]!=null)\r
+            mergeable=false;\r
+          String desc = "";\r
+          if (ae[aa].getDescription()!=null) {\r
+            desc = ae[aa].getDescription();\r
+            if (desc.length()>0) {\r
+              // have imported valid description string\r
+              AeContent[HASDESCSTR]=true;\r
+            }\r
+          }\r
+          String dc = null;//ae[aa].getDisplayCharacter()==null ? "dc" : ae[aa].getDisplayCharacter();\r
+          String ss = null;//ae[aa].getSecondaryStructure()==null ? "ss" : ae[aa].getSecondaryStructure();\r
+          java.awt.Color colour = null;\r
+          if (ae[aa].getGlyphCount()>0) {\r
+            Glyph[] glyphs = ae[aa].getGlyph();\r
+            for (int g=0; g<glyphs.length; g++) {\r
+              if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_SS_3STATE)) {\r
+                ss=glyphs[g].getContent();\r
+                AeContent[HASSECSTR]=true;\r
+              } else if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.PROTEIN_HD_HYDRO)) {\r
+                Cache.log.debug("ignoring hydrophobicity glyph marker.");\r
+                AeContent[HASHPHOB]=true;\r
+                char c=(dc=glyphs[g].getContent()).charAt(0);\r
+                // dc may get overwritten - but we still set the colour.\r
+                colour = new java.awt.Color(c=='+'?255:0,c=='.'?255:0,c=='-'?255:0);\r
+\r
+              } else if (glyphs[g].getDict().equals(org.vamsas.objects.utils.GlyphDictionary.DEFAULT)) {\r
+                dc = glyphs[g].getContent();\r
+                AeContent[HASDC]=true;\r
+              } else {\r
+                Cache.log.debug("Ignoring unknown glyph type "+glyphs[g].getDict());\r
+              }\r
+            }\r
+          }\r
+          float val=0;\r
+          if (ae[aa].getValueCount()>0) {\r
+            AeContent[HASVALS]=true;\r
+            if (ae[aa].getValueCount()>1) {\r
+              Cache.log.warn("ignoring additional "+(ae[aa].getValueCount()-1)+"values in annotation element.");\r
+            }\r
+            val = ae[aa].getValue(0);\r
+          }\r
+          if (colour==null) {\r
+            anot[row][pos]=new jalview.datamodel.Annotation((dc!=null) ? dc : "", desc, (ss!=null)?ss.charAt(0):' ', val);\r
+          } else {\r
+            anot[row][pos]=new jalview.datamodel.Annotation((dc!=null) ? dc : "", desc, (ss!=null)?ss.charAt(0):' ', val, colour);\r
+          }\r
+        } else {\r
+          Cache.log.warn("Ignoring out of bound annotation element "+aa+" in "+annotation.getVorbaId().getId());\r
+        }\r
+      }\r
+      // decide on how many annotation rows are needed.\r
+      if (mergeable) {\r
+        for (int i=0; i<anot[0].length;i++) {\r
+          if (anot[1][i]!=null) {\r
+            anot[0][i] = anot[1][i];\r
+            anot[0][i].description = anot[0][i].description+" (after)";\r
+            AeContent[HASDESCSTR]=true; // we have valid description string data\r
+            anot[1][i] = null;\r
+          }\r
+        }\r
+        anot[1] = null;\r
+      } else {\r
+        for (int i=0; i<anot[0].length;i++) {\r
+          anot[1][i].description = anot[1][i].description+" (after)";\r
+        }\r
+      }\r
+      return new Object[] { AeContent, rangeMap, anot[0], anot[1] };\r
+    } else {\r
+      // no annotations to parse. Just return an empty annotationElement[] array.\r
+      return new Object[] { AeContent, rangeMap, anot[0], anot[1] };\r
+    }\r
+    // return null;\r
+  }\r
+  /**\r
+   * @param jal the jalview alignment to which the annotation will be attached (ideally - freshly updated from corresponding vamsas alignment)\r
+   * @param annotation\r
+   * @return unbound jalview alignment annotation object.\r
+   */\r
+  private jalview.datamodel.AlignmentAnnotation getjAlignmentAnnotation(jalview.datamodel.AlignmentI jal, org.vamsas.objects.core.RangeAnnotation annotation) {\r
+    jalview.datamodel.AlignmentAnnotation jan =null;\r
+    if (annotation==null)\r
+      return null;\r
+    // boolean hasSequenceRef=annotation.getClass().equals(org.vamsas.objects.core.AlignmentSequenceAnnotation.class);\r
+    //boolean hasProvenance=hasSequenceRef || (annotation.getClass().equals(org.vamsas.objects.core.AlignmentAnnotation.class));\r
+    /*int se[] = getBounds(annotation);\r
+    if (se==null)\r
+      se=new int[] {0,jal.getWidth()-1};\r
+     */\r
+    Object[] parsedRangeAnnotation = parseRangeAnnotation(annotation);\r
+    String a_label=annotation.getLabel();\r
+    String a_descr=annotation.getDescription();\r
+    if (a_label==null || a_label.length()==0) {\r
+      a_label = annotation.getType();\r
+      if (a_label.length()==0)\r
+        a_label = "Unamed annotation";\r
+    }\r
+    if (a_descr==null || a_descr.length()==0) {\r
+      a_descr = "Annotation of type '"+annotation.getType()+"'";\r
+    }\r
+    if (parsedRangeAnnotation==null) {\r
+      Cache.log.debug("Inserting empty annotation row elements for a whole-alignment annotation.");\r
+      \r
+      \r
+    } else {\r
+      if (parsedRangeAnnotation[3]!=null) {\r
+        Cache.log.warn("Ignoring 'After' annotation row in "+annotation.getVorbaId());\r
+      }\r
+      jalview.datamodel.Annotation[] arow = (jalview.datamodel.Annotation[]) parsedRangeAnnotation[2];\r
+      boolean[] has=(boolean[])parsedRangeAnnotation[0];\r
+      // 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\r
+      /*if ((annotation.getClass().equals(org.vamsas.objects.core.AlignmentAnnotation.class) && ((org.vamsas.objects.core.AlignmentAnnotation)annotation).getGraph())\r
+          || (hasSequenceRef=true && ((org.vamsas.objects.core.AlignmentSequenceAnnotation)annotation).getGraph())) {\r
+      */\r
+      if (has[HASVALS]) {\r
+        // make bounds and automatic description strings for jalview user's benefit (these shouldn't be written back to vamsas document)\r
+        boolean first=true;\r
+        float min=0,max=1;\r
+        int lastval=0;\r
+        for (int i=0;i<arow.length; i++) {\r
+          if (arow[i]!=null) {\r
+            if (i-lastval>1) {\r
+              // do some interpolation *between* points\r
+              if (arow[lastval]!=null) {\r
+                float interval = arow[i].value-arow[lastval].value;\r
+                interval/=i-lastval;\r
+                float base = arow[lastval].value;\r
+                for (int ip=lastval+1,np=0; ip<i; np++,ip++) {\r
+                  arow[ip] = new jalview.datamodel.Annotation("","",' ', interval*np+base);\r
+                  // NB - Interpolated points don't get a tooltip and description.\r
+                }\r
+              }\r
+            }\r
+            lastval=i;\r
+            // check range - shouldn't we have a min and max property in the annotation object ?\r
+            if (first) { min=max=arow[i].value; first=false;}\r
+            else { if (arow[i].value<min) { min=arow[i].value; }\r
+            else if (arow[i].value>max) { max=arow[i].value; }\r
+            }\r
+            // make tooltip and display char value\r
+            if (!has[HASDESCSTR]) arow[i].description = arow[i].value + "";\r
+            if (!has[HASDC]) arow[i].displayCharacter=arow[i].value+"";\r
+          } \r
+        }\r
+        int type=jalview.datamodel.AlignmentAnnotation.LINE_GRAPH;\r
+        if (has[HASHPHOB]) {\r
+          type = jalview.datamodel.AlignmentAnnotation.BAR_GRAPH;\r
+        }\r
+        jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow, min, max, type);\r
+      } else {\r
+        jan = new jalview.datamodel.AlignmentAnnotation(a_label, a_descr, arow);\r
+        jan.setThreshold(null);\r
+      }\r
+      if (annotation.getLinkCount()>0) {\r
+        Cache.log.warn("Ignoring "+annotation.getLinkCount()+"links added to AlignmentAnnotation.");\r
+      }\r
+      if (annotation.getModifiable()) {\r
+        jan.editable=true;\r
+      }\r
+\r
+      if (annotation.getPropertyCount()>0) {\r
+        // look for special jalview properties\r
+        org.vamsas.objects.core.Property[] props=annotation.getProperty();\r
+        for (int p=0;p<props.length; p++) {\r
+          if (props[p].getName().equalsIgnoreCase("jalview:graphType")) {\r
+            try { \r
+              // probably a jalview annotation graph so recover the visualization hints.\r
+              jan.graph = jalview.datamodel.AlignmentAnnotation.getGraphValueFromString(props[p].getContent());\r
+            } catch (Exception e) {\r
+              Cache.log.debug("Invalid graph type value in jalview:graphType property.");\r
+            }\r
+            try {\r
+              if (annotation.getGroup()!=null && annotation.getGroup().length()>0)\r
+                jan.graphGroup = Integer.parseInt(annotation.getGroup());\r
+            } catch (Exception e) {\r
+              Cache.log.info("UNIMPLEMENTED : Couldn't parse non-integer group value for setting graphGroup correctly.");\r
+            }\r
+          }\r
+        }\r
+      }\r
+\r
+      return jan;\r
+\r
+    } \r
+\r
+    return null;\r
+  }\r
+\r
+  private SequenceFeature getJalviewSeqFeature(RangeAnnotation dseta) {\r
+    int[] se = getBounds(dseta);\r
+    SequenceFeature sf = new jalview.datamodel.SequenceFeature(dseta.getType(),\r
+        dseta.getDescription(), dseta.getStatus(), se[0], se[1], dseta\r
+        .getGroup());\r
+    if (dseta.getLinkCount() > 0)\r
+    {\r
+      Link[] links = dseta.getLink();\r
+      for (int i = 0; i < links.length; i++)\r
+      {\r
+        sf.addLink(links[i].getContent() + "|" + links[i].getHref());\r
+      }\r
+    }\r
+    return sf;\r
+  }\r
+\r
+  /**\r
+   * get real bounds of a RangeType's specification. start and end are an\r
+   * inclusive range within which all segments and positions lie.\r
+   * TODO: refactor to vamsas utils\r
+   * @param dseta\r
+   * @return int[] { start, end}\r
+   */\r
+  private int[] getBounds(RangeType dseta) {\r
+    if (dseta != null)\r
+    {\r
+      int[] se = null;\r
+      if (dseta.getSegCount()>0 && dseta.getPosCount()>0)\r
+        throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");\r
+      if (dseta.getSegCount() > 0)\r
+      {\r
+        se = getSegRange(dseta.getSeg(0),true);\r
+        for (int s = 1, sSize = dseta.getSegCount(); s < sSize; s++)\r
+        {\r
+          int nse[] = getSegRange(dseta.getSeg(s), true);\r
+          if (se[0] > nse[0])\r
+            se[0] = nse[0];\r
+          if (se[1] < nse[1])\r
+            se[1] = nse[1];\r
+        }\r
+      }\r
+      if (dseta.getPosCount() > 0)\r
+      {\r
+        // could do a polarity for pos range too. and pass back indication of discontinuities.\r
+        int pos = dseta.getPos(0).getI();\r
+        se = new int[] { pos, pos };\r
+        for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)\r
+        {\r
+          pos = dseta.getPos(p).getI();\r
+          if (se[0] > pos)\r
+            se[0] = pos;\r
+          if (se[1] < pos)\r
+            se[1] = pos;\r
+        }\r
+      }\r
+      return se;\r
+    }\r
+    return null;\r
+  }\r
+  /**\r
+   * map from a rangeType's internal frame to the referenced object's coordinate frame.\r
+   * @param dseta\r
+   * @return int [] { ref(pos)...} for all pos in rangeType's frame.\r
+   */\r
+  private int[] getMapping(RangeType dseta) {\r
+    Vector posList=new Vector();\r
+    if (dseta != null)\r
+    {\r
+      int[] se = null;\r
+      if (dseta.getSegCount()>0 && dseta.getPosCount()>0)\r
+        throw new Error("Invalid vamsas RangeType - cannot resolve both lists of Pos and Seg from choice!");\r
+      if (dseta.getSegCount() > 0)\r
+      {\r
+        for (int s = 0, sSize = dseta.getSegCount(); s < sSize; s++)\r
+        {\r
+          se = getSegRange(dseta.getSeg(s), false);\r
+          int se_end=se[1-se[2]]+(se[2]==0 ? 1 : -1);\r
+          for (int p=se[se[2]]; p!=se_end; p+=se[2]==0 ? 1 : -1 ) {\r
+            posList.add(new Integer(p));\r
+          }\r
+        }\r
+      } \r
+      else if (dseta.getPosCount() > 0)\r
+      {\r
+        int pos = dseta.getPos(0).getI();\r
+\r
+        for (int p = 0, pSize = dseta.getPosCount(); p < pSize; p++)\r
+        {\r
+          pos = dseta.getPos(p).getI();\r
+          posList.add(new Integer(pos));\r
+        }\r
+      }\r
+    }\r
+    if (posList!=null && posList.size()>0) {\r
+      int[] range=new int[posList.size()];\r
+      for (int i=0; i<range.length; i++)\r
+        range[i] = ((Integer)posList.elementAt(i)).intValue();\r
+      posList.clear();\r
+      return range;\r
+    }\r
+    return null;\r
+  }\r
+  /* not needed now. \r
+   * Provenance getVamsasProvenance(jalview.datamodel.Provenance jprov) {\r
+    jalview.datamodel.ProvenanceEntry[] entries = null;\r
+    // TODO: fix App and Action here.\r
+    Provenance prov = new Provenance();\r
+    org.exolab.castor.types.Date date = new org.exolab.castor.types.Date(\r
+        new java.util.Date());\r
+    Entry provEntry;\r
+\r
+    if (jprov != null)\r
+    {\r
+      entries = jprov.getEntries();\r
+      for (int i = 0; i < entries.length; i++)\r
+      {\r
+        provEntry = new Entry();\r
+        try\r
+        {\r
+          date = new org.exolab.castor.types.Date(entries[i].getDate());\r
+        } catch (Exception ex)\r
+        {\r
+          ex.printStackTrace();\r
+\r
+          date = new org.exolab.castor.types.Date(entries[i].getDate());\r
+        }\r
+        provEntry.setDate(date);\r
+        provEntry.setUser(entries[i].getUser());\r
+        provEntry.setAction(entries[i].getAction());\r
+        prov.addEntry(provEntry);\r
+      }\r
+    }\r
+    else\r
+    {\r
+      provEntry = new Entry();\r
+      provEntry.setDate(date);\r
+      provEntry.setUser(System.getProperty("user.name")); // TODO: ext string\r
+      provEntry.setApp("JVAPP"); // TODO: ext string\r
+      provEntry.setAction(action);\r
+      prov.addEntry(provEntry);\r
+    }\r
+\r
+    return prov;\r
+  }\r
+   */\r
+  jalview.datamodel.Provenance getJalviewProvenance(Provenance prov) {\r
+    // TODO: fix App and Action entries and check use of provenance in jalview.\r
+    jalview.datamodel.Provenance jprov = new jalview.datamodel.Provenance();\r
+    for (int i = 0; i < prov.getEntryCount(); i++)\r
+    {\r
+      jprov.addEntry(prov.getEntry(i).getUser(), prov.getEntry(i).getAction(),\r
+          prov.getEntry(i).getDate().toDate(), prov.getEntry(i).getId());\r
+    }\r
+\r
+    return jprov;\r
+  }\r
+\r
+  /**\r
+   * \r
+   * @return default initial provenance list for a Jalview created vamsas\r
+   *         object.\r
+   */\r
+  Provenance dummyProvenance() {\r
+    return dummyProvenance(null);\r
+  }\r
+\r
+  Entry dummyPEntry(String action) {\r
+    Entry entry = new Entry();\r
+    entry.setApp(this.provEntry.getApp());\r
+    if (action != null)\r
+      entry.setAction(action);\r
+    else\r
+      entry.setAction("created.");\r
+    entry.setDate(new org.exolab.castor.types.Date(new java.util.Date()));\r
+    entry.setUser(this.provEntry.getUser());\r
+    return entry;\r
+  }\r
+\r
+  Provenance dummyProvenance(String action) {\r
+    Provenance prov = new Provenance();\r
+    prov.addEntry(dummyPEntry(action));\r
+    return prov;\r
+  }\r
+\r
+  void addProvenance(Provenance p, String action) {\r
+    p.addEntry(dummyPEntry(action));\r
+  }\r
+\r
+}\r