fixed update of existing appdata jar entry bug (raised a Duplicate zipEnty exception)
[vamsas.git] / src / uk / ac / vamsas / client / simpleclient / VamsasArchive.java
1 package uk.ac.vamsas.client.simpleclient;
2
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.DataOutputStream;
6 import java.io.File;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InputStreamReader;
10 import java.io.OutputStream;
11 import java.io.OutputStreamWriter;
12 import java.io.PrintWriter;
13 import java.util.Hashtable;
14 import java.util.Iterator;
15 import java.util.Vector;
16 import java.util.jar.JarEntry;
17 import java.util.jar.JarOutputStream;
18 import java.util.jar.Manifest;
19
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22
23 import uk.ac.vamsas.client.AppDataOutputStream;
24 import uk.ac.vamsas.client.ClientHandle;
25 import uk.ac.vamsas.client.IVorbaIdFactory;
26 import uk.ac.vamsas.client.SessionHandle;
27 import uk.ac.vamsas.client.UserHandle;
28 import uk.ac.vamsas.client.Vobject;
29 import uk.ac.vamsas.client.VorbaIdFactory;
30 import uk.ac.vamsas.client.VorbaXmlBinder;
31 import uk.ac.vamsas.objects.core.ApplicationData;
32 import uk.ac.vamsas.objects.core.VAMSAS;
33 import uk.ac.vamsas.objects.core.VamsasDocument;
34 import uk.ac.vamsas.objects.utils.AppDataReference;
35 import uk.ac.vamsas.objects.utils.DocumentStuff;
36 import uk.ac.vamsas.objects.utils.ProvenanceStuff;
37 import uk.ac.vamsas.objects.utils.document.VersionEntries;
38
39 /**
40  * Class for high-level io and Jar manipulation involved in creating 
41  * or updating a vamsas archive (with backups).
42  * Writes to a temporary file and then swaps new file for backup.
43  * uses the sessionFile locking mechanism for safe I/O
44  * @author jimp
45  *
46  */
47 public class VamsasArchive {
48   private static Log log = LogFactory.getLog(VamsasArchive.class);
49   /**
50    * Access original document if it exists, and get VAMSAS root objects.
51    * @return vector of vamsas roots from original document
52    * @throws IOException
53    */
54   public static Vobject[] getOriginalRoots(VamsasArchive ths) throws IOException, 
55   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
56     VamsasArchiveReader oReader = ths.getOriginalArchiveReader();
57     if (oReader!=null) {
58       
59       if (oReader.isValid()) {
60         InputStreamReader vdoc = new InputStreamReader(oReader.getVamsasDocumentStream());
61         VamsasDocument doc = VamsasDocument.unmarshal(vdoc);
62         if (doc!=null) 
63           return doc.getVAMSAS();
64         // TODO ensure embedded appDatas are garbage collected to save memory
65       } else {
66         InputStream vxmlis = oReader.getVamsasXmlStream();
67         if (vxmlis!=null) { // Might be an old vamsas file.
68           BufferedInputStream ixml = new BufferedInputStream(oReader.getVamsasXmlStream());
69           InputStreamReader vxml = new InputStreamReader(ixml);
70           VAMSAS root[] = new VAMSAS[1];
71           root[0] = VAMSAS.unmarshal(vxml);
72           if (root[0]!=null)
73             return root;
74         }
75       }
76     }
77     return null;
78   }
79   /**
80    * Access the original vamsas document for a VamsasArchive class, and return it.
81    * Users of the VamsasArchive class should use the getVamsasDocument method to retrieve
82    * the current document - only use this one if you want the 'backup' version.
83    * TODO: catch OutOfMemoryError - they are likely to occur here.
84    * NOTE: vamsas.xml datastreams are constructed as 'ALPHA_VERSION' vamsas documents.
85    * @param ths
86    * @return null if no document exists.
87    * @throws IOException
88    * @throws org.exolab.castor.xml.MarshalException
89    * @throws org.exolab.castor.xml.ValidationException
90    */
91   public static VamsasDocument getOriginalVamsasDocument(VamsasArchive ths) throws IOException, 
92   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
93     return VamsasArchive.getOriginalVamsasDocument(ths, null);
94   } 
95   /**
96    * Uses VorbaXmlBinder to retrieve the VamsasDocument from the original archive referred to by ths
97    * @param ths
98    * @param vorba
99    * @return
100    * @throws IOException
101    * @throws org.exolab.castor.xml.MarshalException
102    * @throws org.exolab.castor.xml.ValidationException
103    */
104   public static VamsasDocument getOriginalVamsasDocument(VamsasArchive ths, VorbaIdFactory vorba) throws IOException, 
105   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
106     VamsasArchiveReader oReader = ths.getOriginalArchiveReader();
107     if (oReader!=null) {
108       ths.setVorba(vorba);
109       return ths.vorba.getVamsasDocument(oReader);
110     }
111     // otherwise - there was no valid original document to read.
112     return null;    
113   }
114   /**
115    * destination of new archive data (tempfile if virginarchive=true, original archive location otherwise)
116    */
117   java.io.File archive=null;
118   /**
119    * locked IO handler for new archive file
120    */
121   SessionFile rchive=null;
122   /**
123    * original archive file to be updated (or null if virgin) where new data will finally reside
124    */
125   java.io.File original=null;
126   /**
127    * original archive IO handler
128    */
129   SessionFile odoclock = null;
130   Lock destinationLock = null;
131   /**
132    * Original archive reader class
133    */
134   VamsasArchiveReader odoc = null;
135   /**
136    * true if a real vamsas document is being written.
137    */
138   boolean vamsasdocument=true;
139   /**
140    * Output stream for archived data
141    */
142   JarOutputStream newarchive=null;
143   /**
144    * JarEntries written to archive
145    */
146   Hashtable entries = null;
147   
148   /**
149    * true if we aren't just updating an archive
150    */
151   private boolean virginArchive=false;
152   
153   /**
154    * name of backup of existing archive that has been updated/overwritten.
155    * only one backup will be made - and this is it.
156    */
157   File originalBackup = null;
158   
159   boolean donotdeletebackup=false;
160   private final int _TRANSFER_BUFFER=4096*4;
161   protected SimpleDocument vorba = null;
162   /**
163    * LATER: ? CUT'n'Paste error ?
164    * Access and return current vamsas Document, if it exists, or create a new one 
165    * (without affecting VamsasArchive object state - so is NOT THREAD SAFE)
166    * _TODO: possibly modify internal state to lock low-level files 
167    * (like the IClientDocument interface instance constructer would do) 
168    * @see org.vamsas.simpleclient.VamsasArchive.getOriginalVamsasDocument for additional caveats
169    * 
170    * @return
171    * @throws IOException
172    * @throws org.exolab.castor.xml.MarshalException
173    * @throws org.exolab.castor.xml.ValidationException
174    * ????? where does this live JBPNote ?
175    */
176   private VamsasDocument _doc=null;
177   
178   /**
179    * Create a new vamsas archive
180    * File locks are made immediately to avoid contention
181    *  
182    * @param archive - file spec for new vamsas archive
183    * @param vamsasdocument true if archive is to be a fully fledged vamsas document archive
184    * @throws IOException if call to accessOriginal failed for updates, or openArchive failed.
185    */
186   public VamsasArchive(File archive, boolean vamsasdocument) throws IOException {
187     this(archive, false, vamsasdocument, null);
188   }
189   public VamsasArchive(File archive, boolean vamsasdocument, boolean overwrite) throws IOException {
190     this(archive, overwrite, vamsasdocument, null);
191   }
192   /**
193    * Constructor for accessing Files under file-lock management (ie a session file)
194    * @param archive
195    * @param vamsasdocument
196    * @param overwrite
197    * @throws IOException
198    */
199   public VamsasArchive(VamsasFile archive, boolean vamsasdocument, boolean overwrite) throws IOException {
200     this(archive.sessionFile, overwrite, vamsasdocument, archive);
201     // log.debug("using non-functional lock-IO stream jar access constructor");
202   }
203   /**
204    * read and write to archive - will not overwrite original contents, and will always write an up to date vamsas document structure.
205    * @param archive
206    * @throws IOException
207    */
208   public VamsasArchive(VamsasFile archive) throws IOException {
209     this(archive, true, false); 
210   }
211   /**
212    * 
213    * @param archive file to write
214    * @param overwrite true if original contents should be deleted
215    * @param vamsasdocument true if a proper VamsasDocument archive is to be written.
216    * @param extantLock SessionFile object holding a lock for the <object>archive</object> 
217    * @throws IOException
218    */
219   public VamsasArchive(File archive, boolean overwrite, boolean vamsasdocument, SessionFile extantLock) throws IOException {
220     super();
221     if (archive==null || (archive!=null && !(archive.getAbsoluteFile().getParentFile().canWrite() && (!archive.exists() || archive.canWrite())))) {
222       log.fatal("Expect Badness! -- Invalid parameters for VamsasArchive constructor:"+((archive!=null) 
223           ? "File cannot be overwritten." : "Null Object not valid constructor parameter"));
224       return;
225     }
226     
227     this.vamsasdocument = vamsasdocument;
228     if (archive.exists() && !overwrite) {
229       this.original = archive;
230       if (extantLock!=null) {
231         this.odoclock = extantLock;
232         if (odoclock.fileLock==null || !odoclock.fileLock.isLocked())
233           odoclock.lockFile();
234       } else { 
235         this.odoclock = new SessionFile(archive);
236       }
237       odoclock.lockFile(); // lock the file *immediatly*
238       this.archive = null;       // archive will be a temp file when the open method is called
239       virginArchive=false;
240       try {
241         this.accessOriginal();
242       } catch (IOException e)  {
243         throw new IOException("Lock failed for existing archive"+archive);
244       }
245     } else {
246       this.original = null;
247       this.archive = archive; // archive is written in place.
248       if (extantLock!=null)
249         rchive=extantLock;
250       else
251         rchive = new SessionFile(archive);
252       rchive.lockFile();
253       if (rchive.fileLock==null || !rchive.fileLock.isLocked())
254         throw new IOException("Lock failed for new archive"+archive);
255       rchive.fileLock.getRaFile().setLength(0); // empty the archive.
256       virginArchive = true;
257     }
258     this.openArchive(); // open archive
259   }
260   /**
261    * open original archive file for exclusive (locked) reading.
262    * @throws IOException
263    */
264   private void accessOriginal() throws IOException {
265     if (original!=null && original.exists()) {
266       if (odoclock==null) 
267         odoclock = new SessionFile(original);
268       odoclock.lockFile();
269       if (odoc == null) 
270         odoc = new VamsasArchiveReader(original);
271         // this constructor is not implemented yet odoc = new VamsasArchiveReader(odoclock.fileLock);
272     }
273   }
274   
275   /**
276    * Add unique entry strings to internal JarEntries list.
277    * @param entry
278    * @return true if entry was unique and was added.
279    */
280   private boolean addEntry(String entry) {
281     if (entries==null)
282       entries=new Hashtable();
283     if (log.isDebugEnabled())
284     {   
285       log.debug("validating '"+entry+"' in hash for "+this);
286     }
287     if (entries.containsKey(entry))
288       return false;
289     entries.put(entry, new Integer(entries.size()));
290     return true;
291   }
292   /**
293    * adds named entry to newarchive or returns false.
294    * @param entry
295    * @return true if entry was unique and could be added
296    * @throws IOException if entry name was invalid or a new entry could not be made on newarchive
297    */
298   private boolean addValidEntry(String entry) throws IOException {
299     JarEntry je = new JarEntry(entry);
300     if (!addEntry(entry))
301       return false;
302     newarchive.flush();
303     newarchive.putNextEntry(je);
304     return true;
305   }
306   /**
307    * called by app to get name of backup if it was made.
308    * If this is called, the caller app *must* delete the backup themselves.
309    * @return null or a valid file object
310    */
311   public File backupFile() {
312     
313     if (!virginArchive) {
314       makeBackup();
315       donotdeletebackup=true; // external reference has been made.
316       return ((original!=null) ? originalBackup : null);
317     }
318     return null;
319   }
320   
321   /**
322    * Stops any current write to archive, and reverts to the backup if it exists.
323    * All existing locks on the original will be released. All backup files are removed.
324    */
325   public boolean cancelArchive() {
326     if (newarchive!=null) {
327       try { 
328         newarchive.closeEntry();
329         newarchive.putNextEntry(new JarEntry("deleted"));
330         newarchive.closeEntry();
331         newarchive.close();
332         
333       } catch (Exception e) {
334         log.debug("Whilst closing newarchive",e);
335       };
336       if (!virginArchive) {
337         // then there is something to recover.
338         try {
339           recoverBackup();
340         }
341         catch (Exception e) {
342           log.warn("Problems when trying to cancel Archive "+archive.getAbsolutePath(), e);
343           return false;
344         }
345       }
346       
347     } else {
348       log.warn("Client Error: cancelArchive called before archive("+original.getAbsolutePath()+") has been opened!");
349     }
350     closeAndReset(); // tidy up and release locks.
351     return true;
352   }
353   
354   /**
355    * only do this if you want to destroy the current file output stream
356    *
357    */
358   private void closeAndReset() {
359     if (rchive!=null) {
360       rchive.unlockFile();
361       rchive=null;
362     }
363     if (original!=null) {
364       if (odoc!=null) {
365         odoc.close();
366         odoc=null;
367       }
368       if (archive!=null)
369         archive.delete();
370       if (odoclock!=null) {
371         odoclock.unlockFile();
372         odoclock = null;
373       }
374     }
375     removeBackup();
376     newarchive=null;
377     original=null;
378     entries=null;
379   }
380   /**
381    * Tidies up and closes archive, removing any backups that were created.
382    * NOTE: It is up to the caller to delete the original archive backup obtained from backupFile()
383    * TODO: ensure all extant AppDataReference jar entries are transferred to new Jar
384    * TODO: provide convenient mechanism for generating new unique AppDataReferences and adding them to the document
385    */
386   public void closeArchive() throws IOException {
387     if (newarchive!=null) {
388       newarchive.flush();
389       newarchive.closeEntry();
390       if (!isDocumentWritten())
391         log.warn("Premature closure of archive '"+archive.getAbsolutePath()+"': No document has been written.");
392       newarchive.finish();// close(); // use newarchive.finish(); for a stream IO
393       newarchive.flush();
394       //
395       updateOriginal();
396       closeAndReset();
397     } else {
398       log.warn("Attempt to close archive that has not been opened for writing.");
399     }
400   }
401   /**
402    * Opens and returns the applicationData output stream for the appdataReference string.
403    * @param appdataReference
404    * @return Output stream to write to
405    * @throws IOException
406    */
407   public AppDataOutputStream getAppDataStream(String appdataReference) throws IOException {
408     if (newarchive==null)
409       throw new IOException("Attempt to write to closed VamsasArchive object.");
410     if (addValidEntry(appdataReference)) {
411       return new AppDataOutputStream(newarchive);
412     }
413     return null;
414   }
415   
416   /**
417    * 
418    * @return JarEntry name for the vamsas XML stream in this archive
419    */
420   protected String getDocumentJarEntry() {
421     if (vamsasdocument)
422       return VamsasArchiveReader.VAMSASDOC;
423     return VamsasArchiveReader.VAMSASXML;
424   }
425   /**
426    * Safely initializes the VAMSAS XML document Jar Entry. 
427    * @return Writer to pass to the marshalling function.
428    * @throws IOException if a document entry has already been written. 
429    */
430   public PrintWriter getDocumentOutputStream() throws IOException {
431     if (newarchive==null)
432       openArchive();
433     if (!isDocumentWritten()) {
434       try {
435         if (addValidEntry(getDocumentJarEntry())) 
436           return new PrintWriter(new java.io.OutputStreamWriter(newarchive, "UTF-8"));
437       } catch (Exception e) {
438         log.warn("Problems opening XML document JarEntry stream",e);
439       }
440     } else {
441       throw new IOException("Vamsas Document output stream is already written.");
442     }
443     return null;
444   }
445   
446   /**
447    * Access original archive if it exists, pass the reader to the client
448    * Note: this is NOT thread safe and a call to closeArchive() will by necessity 
449    * close and invalidate the VamsasArchiveReader object.
450    * @return null if no original archive exists.
451    */
452   public VamsasArchiveReader getOriginalArchiveReader() throws IOException {
453     if (!virginArchive) {
454       accessOriginal();
455       return odoc;
456     }
457     return null;
458   }
459   /**
460    * returns original document's root vamsas elements.
461    * @return
462    * @throws IOException
463    * @throws org.exolab.castor.xml.MarshalException
464    * @throws org.exolab.castor.xml.ValidationException
465    */
466   public Vobject[] getOriginalRoots() throws IOException, 
467   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException  {
468     return VamsasArchive.getOriginalRoots(this);
469   }
470   /**
471    * @return original document or a new empty document (with default provenance)
472    * @throws IOException
473    * @throws org.exolab.castor.xml.MarshalException
474    * @throws org.exolab.castor.xml.ValidationException
475    */
476   public VamsasDocument getVamsasDocument() throws IOException, 
477   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
478     return getVamsasDocument("org.vamsas.simpleclient.VamsasArchive", "Created new empty document", null);
479   }
480   /**
481    * Return the original document or a new empty document with initial provenance entry.
482    * @param provenance_user (null sets user to be the class name)
483    * @param provenance_action (null sets action to be 'created new document')
484    * @param version (null means use latest version)
485    * @return (original document or a new vamsas document with supplied provenance and version info)
486    * @throws IOException
487    * @throws org.exolab.castor.xml.MarshalException
488    * @throws org.exolab.castor.xml.ValidationException
489    */
490   public VamsasDocument getVamsasDocument(String provenance_user, String provenance_action, String version) throws IOException, 
491   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
492     if (_doc!=null)
493       return _doc;
494     _doc = getOriginalVamsasDocument(this, getVorba());
495     if (_doc!=null)
496       return _doc;
497     // validate parameters
498     if (provenance_user==null)
499       provenance_user = "org.vamsas.simpleclient.VamsasArchive";
500     if (provenance_action == null)
501       provenance_action="Created new empty document";
502     if (version==null)
503       version = VersionEntries.latestVersion();
504     // Create a new document and return it
505     _doc = DocumentStuff.newVamsasDocument(new VAMSAS[] { new VAMSAS()}, 
506         ProvenanceStuff.newProvenance(provenance_user, provenance_action), version);
507     return _doc;
508   }
509   /**
510    * @return Returns the current VorbaIdFactory for the archive.
511    */
512   public VorbaIdFactory getVorba() {
513     if (vorba==null)
514       vorba = new SimpleDocument("simpleclient.VamsasArchive");
515     return vorba.getVorba();
516   }
517   /**
518    * @return true if Vamsas Document has been written to archive
519    */
520   protected boolean isDocumentWritten() {
521     if (newarchive==null)
522       log.warn("isDocumentWritten() called for unopened archive.");
523     if (entries!=null) {
524       if (entries.containsKey(getDocumentJarEntry()))
525         return true;
526     }
527     return false;
528   }
529   private void makeBackup() {
530     if (!virginArchive) {
531       if (originalBackup==null && original!=null && original.exists()) {
532         try {
533           accessOriginal();
534           originalBackup = odoclock.backupSessionFile(null, original.getName(), ".bak", original.getParentFile());
535         }
536         catch (IOException e) {
537           log.warn("Problem whilst making a backup of original archive.",e);
538         }
539       }
540     }
541   }
542   /**
543    * opens the new archive ready for writing. If the new archive is replacing an existing one, 
544    * then the existing archive will be locked, and the new archive written to a temporary file. 
545    * The new archive will be put in place once close() is called.
546    * @param doclock LATER - pass existing lock on document, if it exists.... no need yet?
547    * @throws IOException
548    */
549   private void openArchive() throws IOException {
550     
551     if (newarchive!=null) {
552       log.warn("openArchive() called multiple times.");
553       throw new IOException("Vamsas Archive '"+archive.getAbsolutePath()+"' is already open.");
554     }
555     if (archive==null && (virginArchive || original==null)) {
556       log.warn("openArchive called on uninitialised VamsasArchive object.");
557       throw new IOException("Badly initialised VamsasArchive object - no archive file specified.");
558     }
559     if (!virginArchive) {
560       // lock the original
561       accessOriginal();
562       // make a temporary file to write to
563       archive = File.createTempFile(original.getName(), ".new",original.getParentFile());
564     } else {
565       if (archive.exists())
566         log.warn("New archive file name already in use! Possible lock failure imminent?");
567     }
568     
569     if (rchive==null)
570       rchive = new SessionFile(archive);
571     if (!rchive.lockFile()) 
572       throw new IOException("Failed to get lock on file "+archive);
573     // LATER: locked IO stream based access.
574     Manifest newmanifest = new Manifest();
575     newarchive = new JarOutputStream(rchive.fileLock.getBufferedOutputStream(true), newmanifest);  
576     //newarchive = new JarOutputStream(new BufferedOutputStream(new java.io.FileOutputStream(archive)));  
577     entries = new Hashtable();
578   }
579   public void putVamsasDocument(VamsasDocument doc) throws IOException, 
580   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
581     putVamsasDocument(doc, getVorba());
582   }
583   /**
584    * 
585    * @param doc
586    * @param vorba
587    * @return (vorbaId string, Vobjhash) pairs for last hash of each object in document
588    * @throws IOException
589    * @throws org.exolab.castor.xml.MarshalException
590    * @throws org.exolab.castor.xml.ValidationException
591    */
592   public void putVamsasDocument(VamsasDocument doc, VorbaIdFactory vorba) throws IOException, 
593   org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
594     if (vamsasdocument)
595       doc.setVersion(VersionEntries.latestVersion()); // LATER: ensure this does the correct thing.
596     VorbaXmlBinder.putVamsasDocument(getDocumentOutputStream(), vorba, doc);
597   }
598   
599   /**
600    * recovers the original file's contents from the (temporary) backup. 
601    * @throws Exception if any SessionFile or file removal operations fail.
602    */
603   private void recoverBackup() throws Exception {
604     if (originalBackup!=null) {
605       // backup has been made.
606       // revert from backup and delete it (changing backup filename)
607       if (rchive==null) {
608         rchive = new SessionFile(original);
609       }
610       SessionFile bckup = new SessionFile(originalBackup);
611       
612       rchive.updateFrom(null, bckup); // recover from backup file.
613       bckup.unlockFile();
614       bckup=null;
615       removeBackup();
616     }
617   }
618   
619   /**
620    * forget about any backup that was made - removing it first if it was only temporary.
621    */
622   private void removeBackup() {
623     if (originalBackup!=null) {
624       log.debug("Removing backup in "+originalBackup.getAbsolutePath());
625       if (!donotdeletebackup)
626         if (!originalBackup.delete())
627           log.info("VamsasArchive couldn't remove temporary backup "+originalBackup.getAbsolutePath());
628       originalBackup=null;
629     }
630   } 
631   /**
632    * @param vorba the VorbaIdFactory to use for accessing vamsas objects.
633    */
634   public void setVorba(VorbaIdFactory Vorba) {
635     if (Vorba!=null) {
636       if (vorba==null)
637         vorba = new SimpleDocument(Vorba);
638       else
639         vorba.setVorba(Vorba);
640     } else
641       getVorba();
642   }
643   /**
644    * Convenience method to copy over the referred entry from the backup to the new version.
645    * Warning messages are raised if no backup exists or the 
646    * entry doesn't exist in the backed-up original.
647    * Duplicate writes return true - but a warning message will also be raised.
648    * @param AppDataReference
649    * @return true if AppDataReference now exists in the new document
650    * @throws IOException
651    */
652   public boolean transferAppDataEntry(String AppDataReference) throws IOException {
653     return transferAppDataEntry(AppDataReference, AppDataReference);
654   }
655   /**
656    * Validates the AppDataReference: not null and not already written to archive.
657    * @param AppDataReference
658    * @return true if valid. false if not
659    * @throws IOException for really broken references!
660    */
661   protected boolean _validNewAppDataReference(String newAppDataReference) throws IOException {
662     // LATER: Specify valid AppDataReference form in all VamsasArchive handlers
663     if (newAppDataReference==null)
664       throw new IOException("null newAppDataReference!");
665     if (entries.containsKey(newAppDataReference)) {
666       log.warn("Attempt to write '"+newAppDataReference+"' twice! - IGNORED");
667       // LATER: fix me? warning message should raise an exception here.
668       return false;
669     }
670     return true;
671   }
672   /**
673    * Transfers an AppDataReference from old to new vamsas archive, with a name change.
674    * @see transferAppDataEntry(String AppDataReference)
675    * @param AppDataReference
676    * @param NewAppDataReference - AppDataReference in new Archive
677    * @return
678    * @throws IOException
679    */
680   public boolean transferAppDataEntry(String AppDataReference, String NewAppDataReference) throws IOException {
681     if (original==null || !original.exists()) {
682       log.warn("No backup archive exists.");
683       return false;
684     }
685     if (AppDataReference==null)
686       throw new IOException("null AppDataReference!");
687
688     if (!_validNewAppDataReference(NewAppDataReference))
689       return false;
690     
691     accessOriginal();
692     
693     java.io.InputStream adstream = odoc.getAppdataStream(AppDataReference);
694     
695     if (adstream==null) {
696       log.warn("AppDataReference '"+AppDataReference+"' doesn't exist in backup archive.");
697       return false;
698     }
699     
700     java.io.OutputStream adout = getAppDataStream(NewAppDataReference);
701     // copy over the bytes
702     int written=-1;
703     long count=0;
704     byte[] buffer = new byte[_TRANSFER_BUFFER]; // conservative estimate of a sensible buffer
705     do {
706       if ((written = adstream.read(buffer))>-1) {
707         adout.write(buffer, 0, written);
708         log.debug("Transferring "+written+".");
709         count+=written;
710       }
711     } while (written>-1);
712     log.debug("Sucessfully transferred AppData for '"
713         +AppDataReference+"' as '"+NewAppDataReference+"' ("+count+" bytes)");
714     return true;
715   }
716   /**
717    * write data from a stream into an appData reference.
718    * @param AppDataReference - New AppDataReference not already written to archive
719    * @param adstream Source of data for appData reference - read until .read(buffer) returns -1
720    * @return true on success.
721    * @throws IOException for file IO or invalid AppDataReference string
722    */
723   public boolean writeAppdataFromStream(String AppDataReference, java.io.InputStream adstream) throws IOException {
724     if (!_validNewAppDataReference(AppDataReference)) {
725       log.warn("Invalid AppDataReference passed to writeAppdataFromStream");
726       throw new IOException("Invalid AppDataReference! (null, or maybe non-unique)!");
727     }
728       
729     if (AppDataReference==null) {
730       log.warn("null appdata passed.");
731       throw new IOException("Null AppDataReference");
732     }
733     
734     java.io.OutputStream adout = getAppDataStream(AppDataReference);
735     // copy over the bytes
736     int written=-1;
737     long count=0;
738     byte[] buffer = new byte[_TRANSFER_BUFFER]; // conservative estimate of a sensible buffer
739     do {
740       if ((written = adstream.read(buffer))>-1) {
741         adout.write(buffer, 0, written);
742         log.debug("Transferring "+written+".");
743         count+=written;
744       }
745     } while (written>-1);
746     return true;
747   }
748   /**
749    * transfers any AppDataReferences existing in the old document 
750    * that haven't already been transferred to the new one
751    * LATER: do the same for transfers requiring a namechange - more document dependent.
752    *  @return true if data was transferred.
753    */
754   public boolean transferRemainingAppDatas() throws IOException {
755     boolean transfered=false;
756     if (original==null || !original.exists()) {
757       log.warn("No backup archive exists.");
758       return false;
759     }
760     accessOriginal();
761     
762     if (getVorba()!=null) {
763       Vector originalRefs=null;
764       try {
765         originalRefs = vorba.getReferencedEntries(getVamsasDocument(), getOriginalArchiveReader());
766       } catch (Exception e) {
767         log.warn("Problems accessing original document entries!",e);
768       }
769       if (originalRefs!=null) {
770         Iterator ref = originalRefs.iterator();
771         while (ref.hasNext()) {
772           String oldentry = (String) ref.next();
773           if (oldentry!=null && !entries.containsKey(oldentry)) {
774             log.debug("Transferring remaining entry '"+oldentry+"'");
775             transfered |= transferAppDataEntry(oldentry);
776           }
777         }
778       }
779     } 
780     return transfered;
781   }
782   /**
783    * called after archive is written to put file in its final place
784    */
785   private void updateOriginal() {
786     if (!virginArchive) {
787       // make sure original document really is backed up and then overwrite it.
788       if (odoc!=null) {
789         // try to shut the odoc reader.
790         odoc.close();
791         odoc = null;
792       }
793       // Make a backup if it isn't done already
794       makeBackup();
795       try {
796         // copy new Archive data that was writen to a temporary file
797         odoclock.updateFrom(null, rchive);
798       }
799       catch (IOException e) {
800         // LATER: decide if leaving nastily named backup files around is necessary.
801         File backupFile=backupFile();
802         if (backupFile!=null)
803           log.error("Problem updating archive from temporary file! - backup left in '"
804             +backupFile().getAbsolutePath()+"'",e);
805         else
806           log.error("Problems updating, and failed to even make a backup file. Ooops!", e);
807       }
808       // Tidy up if necessary.
809       removeBackup();
810     } else {
811       
812       
813     }
814   }
815 }