1 package org.vamsas.client.simpleclient;
3 import java.io.BufferedInputStream;
4 import java.io.BufferedOutputStream;
5 import java.io.DataOutputStream;
7 import java.io.IOException;
8 import java.io.InputStream;
9 import java.io.InputStreamReader;
10 import java.io.PrintWriter;
11 import java.util.Hashtable;
12 import java.util.jar.JarEntry;
13 import java.util.jar.JarOutputStream;
15 import org.apache.commons.logging.Log;
16 import org.apache.commons.logging.LogFactory;
17 import org.vamsas.client.object;
18 import org.vamsas.objects.core.ApplicationData;
19 import org.vamsas.objects.core.VAMSAS;
20 import org.vamsas.objects.core.VamsasDocument;
21 import org.vamsas.objects.utils.DocumentStuff;
22 import org.vamsas.objects.utils.ProvenanceStuff;
23 import org.vamsas.objects.utils.document.VersionEntries;
26 * Class for high-level io and Jar manipulation involved in creating
27 * or updating a vamsas archive (with backups).
28 * Writes to a temporary file and then swaps new file for backup.
29 * uses the sessionFile locking mechanism for safe I/O
33 public class VamsasArchive {
34 private static Log log = LogFactory.getLog(VamsasArchive.class);
36 * destination of new archive data (tempfile if virginarchive=true, original archive location otherwise)
38 java.io.File archive=null;
40 * locked IO handler for new archive file
42 SessionFile rchive=null;
44 * original archive file to be updated (or null if virgin) where new data will finally reside
46 java.io.File original=null;
48 * original archive IO handler
50 SessionFile odoclock = null;
52 * Original archive reader class
54 VamsasArchiveReader odoc = null;
56 * true if a real vamsas document is being written.
58 boolean vamsasdocument=true;
60 * Output stream for archived data
62 JarOutputStream newarchive=null;
64 * JarEntries written to archive
66 Hashtable entries = null;
68 * true if we aren't just updating an archive
70 private boolean virginArchive=false;
72 * Create a new vamsas archive
73 * File locks are made immediately to avoid contention
75 * @param archive - file spec for new vamsas archive
76 * @param vamsasdocument true if archive is to be a fully fledged vamsas document archive
77 * @throws IOException if call to accessOriginal failed for updates, or openArchive failed.
79 public VamsasArchive(File archive, boolean vamsasdocument) throws IOException {
81 if (archive==null || (archive!=null && !archive.canWrite())) {
82 log.fatal("Invalid parameters for VamsasArchive constructor:"+((archive!=null)
83 ? "File cannot be overwritten." : "Null Object not valid constructor parameter"));
85 this.vamsasdocument = vamsasdocument;
86 if (archive.exists()) {
87 this.original = archive;
88 this.archive = null; // archive will be a temp file when the open method is called
91 this.accessOriginal();
92 } catch (IOException e) {
93 throw new IOException("Lock failed for existing archive"+archive);
97 this.archive = archive; // archive is written in place.
103 * name of backup of existing archive that has been updated/overwritten.
104 * onlu one backup will be made - and this is it.
106 File originalBackup = null;
108 private void makeBackup() {
109 if (!virginArchive) {
110 if (originalBackup==null && original!=null && original.exists()) {
113 originalBackup = odoclock.backupSessionFile(null, original.getName(), ".bak", original.getParentFile());
115 catch (IOException e) {
116 log.warn("Problem whilst making a backup of original archive.",e);
123 * called after archive is written to put file in its final place
124 * TODO: FINISH ?? original should have sessionFile, and archive should also have sessionFile
126 private void updateOriginal() {
127 if (!virginArchive) {
128 // make sure original document really is backed up and then overwrite it.
130 // try to shut the odoc reader.
134 // Make a backup if it isn't done already
135 if (originalBackup==null)
138 // copy new Archive data that was writen to a temporary file
139 odoclock.updateFrom(null, rchive);
141 catch (IOException e) {
142 log.error("Problem updating archive from temporary file! - backup in '"
143 +backupFile().getAbsolutePath()+"'",e);
146 // don't need to do anything.
150 * called by app to get name of backup if it was made.
151 * @return null or a valid file object
153 public File backupFile() {
155 if (!virginArchive) {
157 return ((original!=null) ? originalBackup : null);
164 * @return JarEntry name for the vamsas XML stream in this archive
166 protected String getDocumentJarEntry() {
168 return VamsasArchiveReader.VAMSASDOC;
169 return VamsasArchiveReader.VAMSASXML;
173 * @return true if Vamsas Document has been written to archive
175 protected boolean isDocumentWritten() {
176 if (newarchive==null)
177 log.warn("isDocumentWritten called for unopened archive.");
179 if (entries.containsKey(getDocumentJarEntry()))
185 * Add unique entry strings to internal JarEntries list.
187 * @return true if entry was unique and was added.
189 private boolean addEntry(String entry) {
191 entries=new Hashtable();
192 if (entries.containsKey(entry))
194 entries.put(entry, new Integer(entries.size()));
198 * adds named entry to newarchive or returns false.
200 * @return true if entry was unique and could be added
201 * @throws IOException if entry name was invalid or a new entry could not be made on newarchive
203 private boolean addValidEntry(String entry) throws IOException {
204 JarEntry je = new JarEntry(entry);
205 if (!addEntry(entry))
207 newarchive.putNextEntry(je);
212 * opens the new archive ready for writing. If the new archive is replacing an existing one,
213 * then the existing archive will be locked, and the new archive written to a temporary file.
214 * The new archive will be put in place once close() is called.
215 * @throws IOException
217 private void openArchive() throws IOException {
219 if (newarchive!=null) {
220 log.warn("openArchive() called multiple times.");
221 throw new IOException("Vamsas Archive '"+archive.getAbsolutePath()+"' is already open.");
223 if (archive==null && (virginArchive || original==null)) {
224 log.warn("openArchive called on uninitialised VamsasArchive object.");
225 throw new IOException("Badly initialised VamsasArchive object - no archive file specified.");
227 if (!virginArchive) {
230 // make a temporary file to write to
231 archive = File.createTempFile(original.getName(), ".new",original.getParentFile());
233 if (archive.exists())
234 log.warn("New archive file name already in use! Possible lock failure imminent?");
237 rchive = new SessionFile(archive);
239 newarchive = new JarOutputStream(new BufferedOutputStream(new java.io.FileOutputStream(archive)));
240 entries = new Hashtable();
243 * Safely initializes the VAMSAS XML document Jar Entry.
244 * @return Writer to pass to the marshalling function.
245 * @throws IOException if a document entry has already been written.
247 public PrintWriter getDocumentOutputStream() throws IOException {
248 if (newarchive==null)
250 if (!isDocumentWritten()) {
252 if (addValidEntry(getDocumentJarEntry()))
253 return new PrintWriter(new java.io.OutputStreamWriter(newarchive, "UTF-8"));
254 } catch (Exception e) {
255 log.warn("Problems opening XML document JarEntry stream",e);
258 throw new IOException("Vamsas Document output stream is already written.");
263 * Opens and returns the applicationData output stream for the appdataReference string.
264 * @param appdataReference
265 * @return Output stream to write to
266 * @throws IOException
268 public AppDataOutputStream getAppDataStream(String appdataReference) throws IOException {
269 if (newarchive!=null)
271 if (addValidEntry(appdataReference)) {
272 return new AppDataOutputStream(newarchive);
278 * Stops any current write to archive, and reverts to the backup if it exists.
279 * All existing locks on the original will be released.
281 public boolean cancelArchive() {
282 if (newarchive!=null) {
286 } catch (Exception e) {};
287 if (!virginArchive) {
288 // then there is something to recover.
289 if (originalBackup!=null) {
290 // backup has been made.
291 // revert from backup and delete it (changing backup filename)
293 rchive = new SessionFile(original);
295 SessionFile bckup = new SessionFile(originalBackup);
298 rchive.updateFrom(null, bckup); // recover from backup file.
301 originalBackup.delete();
304 catch (Exception e) {
305 log.warn("Problems when trying to cancel Archive "+archive.getAbsolutePath(), e);
309 // original is untouched
310 // just delete temp files
315 log.info("cancelArchive called before archive("+original.getAbsolutePath()+") has been opened!");
322 * only do this if you want to destroy the current file output stream
325 private void closeAndReset() {
330 if (original!=null) {
337 if (odoclock!=null) {
338 odoclock.unlockFile();
347 private final int _TRANSFER_BUFFER=4096*4;
349 * open original archive file for exclusive (locked) reading.
350 * @throws IOException
352 private void accessOriginal() throws IOException {
353 if (original!=null && original.exists()) {
355 odoclock = new SessionFile(original);
358 odoc = new VamsasArchiveReader(original);
363 * Convenience method to copy over the referred entry from the backup to the new version.
364 * Warning messages are raised if no backup exists or the
365 * entry doesn't exist in the backed-up original.
366 * Duplicate writes return true - but a warning message will also be raised.
367 * @param AppDataReference
368 * @return true if AppDataReference now exists in the new document
369 * @throws IOException
371 public boolean transferAppDataEntry(String AppDataReference) throws IOException {
372 return transferAppDataEntry(AppDataReference, AppDataReference);
375 * Transfers an AppDataReference from old to new vamsas archive, with a name change.
376 * @see transferAppDataEntry(String AppDataReference)
377 * @param AppDataReference
378 * @param NewAppDataReference - AppDataReference in new Archive
380 * @throws IOException
382 public boolean transferAppDataEntry(String AppDataReference, String NewAppDataReference) throws IOException {
383 // TODO: Specify valid AppDataReference form in all VamsasArchive handlers
384 if (AppDataReference==null)
385 throw new IOException("null AppDataReference!");
386 if (original==null || !original.exists()) {
387 log.warn("No backup archive exists.");
390 if (entries.containsKey(NewAppDataReference)) {
391 log.warn("Attempt to write '"+NewAppDataReference+"' twice! - IGNORED");
397 java.io.InputStream adstream = odoc.getAppdataStream(AppDataReference);
399 if (adstream==null) {
400 log.warn("AppDataReference '"+AppDataReference+"' doesn't exist in backup archive.");
404 java.io.OutputStream adout = getAppDataStream(NewAppDataReference);
405 // copy over the bytes
408 byte[] buffer = new byte[_TRANSFER_BUFFER]; // conservative estimate of a sensible buffer
410 if ((written = adstream.read(buffer))>-1) {
411 adout.write(buffer, 0, written);
412 log.debug("Transferring "+written+".");
415 } while (written>-1);
416 log.debug("Sucessfully transferred AppData for '"
417 +AppDataReference+"' as '"+NewAppDataReference+"' ("+count+" bytes)");
421 * Tidies up and closes archive, removing any backups that were created.
422 * NOTE: It is up to the caller to delete the original archive backup obtained from backupFile()
424 public void closeArchive() throws IOException {
425 if (newarchive!=null) {
426 newarchive.closeEntry();
427 if (!isDocumentWritten())
428 log.warn("Premature closure of archive '"+archive.getAbsolutePath()+"': No document has been written.");
433 log.warn("Attempt to close archive that has not been opened for writing.");
437 * Access original archive if it exists, pass the reader to the client
438 * Note: this is NOT thread safe and a call to closeArchive() will by necessity
439 * close and invalidate the VamsasArchiveReader object.
440 * @return null if no original archive exists.
442 public VamsasArchiveReader getOriginalArchiveReader() throws IOException {
443 if (!virginArchive) {
450 * returns original document's root vamsas elements.
452 * @throws IOException
453 * @throws org.exolab.castor.xml.MarshalException
454 * @throws org.exolab.castor.xml.ValidationException
456 public object[] getOriginalRoots() throws IOException,
457 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
458 return VamsasArchive.getOriginalRoots(this);
461 * Access original document if it exists, and get VAMSAS root objects.
462 * @return vector of vamsas roots from original document
463 * @throws IOException
465 public static object[] getOriginalRoots(VamsasArchive ths) throws IOException,
466 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
467 VamsasArchiveReader oReader = ths.getOriginalArchiveReader();
470 if (oReader.isValid()) {
471 InputStreamReader vdoc = new InputStreamReader(oReader.getVamsasDocumentStream());
472 VamsasDocument doc = VamsasDocument.unmarshal(vdoc);
474 return doc.getVAMSAS();
475 // TODO ensure embedded appDatas are garbage collected to save memory
477 InputStream vxmlis = oReader.getVamsasXmlStream();
478 if (vxmlis!=null) { // Might be an old vamsas file.
479 BufferedInputStream ixml = new BufferedInputStream(oReader.getVamsasXmlStream());
480 InputStreamReader vxml = new InputStreamReader(ixml);
481 VAMSAS root[] = new VAMSAS[1];
482 root[0] = VAMSAS.unmarshal(vxml);
491 * Access and return current vamsas Document, if it exists, or create a new one
492 * (without affecting VamsasArchive object state - so is NOT THREAD SAFE)
493 * TODO: possibly modify internal state to lock low-level files
494 * (like the IClientDocument interface instance constructer would do)
495 * @see org.vamsas.simpleclient.VamsasArchive.getOriginalVamsasDocument for additional caveats
498 * @throws IOException
499 * @throws org.exolab.castor.xml.MarshalException
500 * @throws org.exolab.castor.xml.ValidationException
502 public VamsasDocument getVamsasDocument() throws IOException,
503 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
504 VamsasDocument doc = getOriginalVamsasDocument(this);
507 // Create a new document and return it
508 doc = DocumentStuff.newVamsasDocument(new VAMSAS[] { new VAMSAS()},
509 ProvenanceStuff.newProvenance("org.vamsas.simpleclient.VamsasArchive", "Created new empty document")
510 , VersionEntries.latestVersion());
514 * Access the original vamsas document for a VamsasArchive class, and return it.
515 * Users of the VamsasArchive class should use the getVamsasDocument method to retrieve
516 * the current document - only use this one if you want the 'backup' version.
517 * TODO: catch OutOfMemoryError - they are likely to occur here.
518 * NOTE: vamsas.xml datastreams are constructed as 'ALPHA_VERSION' vamsas documents.
520 * @return null if no document exists.
521 * @throws IOException
522 * @throws org.exolab.castor.xml.MarshalException
523 * @throws org.exolab.castor.xml.ValidationException
525 public static VamsasDocument getOriginalVamsasDocument(VamsasArchive ths) throws IOException,
526 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
527 VamsasArchiveReader oReader = ths.getOriginalArchiveReader();
529 if (oReader.isValid()) {
530 InputStreamReader vdoc = new InputStreamReader(oReader.getVamsasDocumentStream());
531 VamsasDocument doc = VamsasDocument.unmarshal(vdoc);
535 // deprecated data handler
536 InputStream vxmlis = oReader.getVamsasXmlStream();
537 if (vxmlis!=null) { // Might be an old vamsas file.
538 BufferedInputStream ixml = new BufferedInputStream(oReader.getVamsasXmlStream());
539 InputStreamReader vxml = new InputStreamReader(ixml);
540 VAMSAS root[] = new VAMSAS[1];
541 root[0] = VAMSAS.unmarshal(vxml);
543 log.debug("Reading old format vamsas.xml into a dummy document.");
544 VamsasDocument doc = DocumentStuff.newVamsasDocument(root,
545 ProvenanceStuff.newProvenance(
546 "org.vamsas.simpleclient.VamsasArchive", // TODO: VAMSAS: decide on 'system' operations provenance form
547 "Vamsas Document constructed from vamsas.xml in <file>"
548 // TODO: VAMSAS: decide on machine readable info embedding in provenance should be done
549 +ths.original+"</file>"), VersionEntries.ALPHA_VERSION);
556 } // otherwise - there was no valid original document to read.