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