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.OutputStream;
11 import java.io.OutputStreamWriter;
12 import java.io.PrintWriter;
13 import java.util.Hashtable;
14 import java.util.jar.JarEntry;
15 import java.util.jar.JarOutputStream;
17 import org.apache.commons.logging.Log;
18 import org.apache.commons.logging.LogFactory;
19 import org.vamsas.client.ClientHandle;
20 import org.vamsas.client.IVorbaIdFactory;
21 import org.vamsas.client.SessionHandle;
22 import org.vamsas.client.UserHandle;
23 import org.vamsas.client.VorbaIdFactory;
24 import org.vamsas.client.VorbaXmlBinder;
25 import org.vamsas.client.object;
26 import org.vamsas.objects.core.ApplicationData;
27 import org.vamsas.objects.core.VAMSAS;
28 import org.vamsas.objects.core.VamsasDocument;
29 import org.vamsas.objects.utils.DocumentStuff;
30 import org.vamsas.objects.utils.ProvenanceStuff;
31 import org.vamsas.objects.utils.document.VersionEntries;
34 * Class for high-level io and Jar manipulation involved in creating
35 * or updating a vamsas archive (with backups).
36 * Writes to a temporary file and then swaps new file for backup.
37 * uses the sessionFile locking mechanism for safe I/O
41 public class VamsasArchive {
42 private static Log log = LogFactory.getLog(VamsasArchive.class);
44 * destination of new archive data (tempfile if virginarchive=true, original archive location otherwise)
46 java.io.File archive=null;
48 * locked IO handler for new archive file
50 SessionFile rchive=null;
52 * original archive file to be updated (or null if virgin) where new data will finally reside
54 java.io.File original=null;
56 * original archive IO handler
58 SessionFile odoclock = null;
60 * Original archive reader class
62 VamsasArchiveReader odoc = null;
64 * true if a real vamsas document is being written.
66 boolean vamsasdocument=true;
68 * Output stream for archived data
70 JarOutputStream newarchive=null;
72 * JarEntries written to archive
74 Hashtable entries = null;
76 * true if we aren't just updating an archive
78 private boolean virginArchive=false;
80 * Create a new vamsas archive
81 * File locks are made immediately to avoid contention
83 * @param archive - file spec for new vamsas archive
84 * @param vamsasdocument true if archive is to be a fully fledged vamsas document archive
85 * @throws IOException if call to accessOriginal failed for updates, or openArchive failed.
87 public VamsasArchive(File archive, boolean vamsasdocument) throws IOException {
89 if (archive==null || (archive!=null && !archive.canWrite())) {
90 log.fatal("Invalid parameters for VamsasArchive constructor:"+((archive!=null)
91 ? "File cannot be overwritten." : "Null Object not valid constructor parameter"));
93 this.vamsasdocument = vamsasdocument;
94 if (archive.exists()) {
95 this.original = archive;
96 this.archive = null; // archive will be a temp file when the open method is called
99 this.accessOriginal();
100 } catch (IOException e) {
101 throw new IOException("Lock failed for existing archive"+archive);
104 this.original = null;
105 this.archive = archive; // archive is written in place.
106 virginArchive = true;
111 * name of backup of existing archive that has been updated/overwritten.
112 * onlu one backup will be made - and this is it.
114 File originalBackup = null;
116 private void makeBackup() {
117 if (!virginArchive) {
118 if (originalBackup==null && original!=null && original.exists()) {
121 originalBackup = odoclock.backupSessionFile(null, original.getName(), ".bak", original.getParentFile());
123 catch (IOException e) {
124 log.warn("Problem whilst making a backup of original archive.",e);
131 * called after archive is written to put file in its final place
132 * TODO: FINISH ?? original should have sessionFile, and archive should also have sessionFile
134 private void updateOriginal() {
135 if (!virginArchive) {
136 // make sure original document really is backed up and then overwrite it.
138 // try to shut the odoc reader.
142 // Make a backup if it isn't done already
143 if (originalBackup==null)
146 // copy new Archive data that was writen to a temporary file
147 odoclock.updateFrom(null, rchive);
149 catch (IOException e) {
150 log.error("Problem updating archive from temporary file! - backup in '"
151 +backupFile().getAbsolutePath()+"'",e);
154 // don't need to do anything.
158 * called by app to get name of backup if it was made.
159 * @return null or a valid file object
161 public File backupFile() {
163 if (!virginArchive) {
165 return ((original!=null) ? originalBackup : null);
171 * @return JarEntry name for the vamsas XML stream in this archive
173 protected String getDocumentJarEntry() {
175 return VamsasArchiveReader.VAMSASDOC;
176 return VamsasArchiveReader.VAMSASXML;
180 * @return true if Vamsas Document has been written to archive
182 protected boolean isDocumentWritten() {
183 if (newarchive==null)
184 log.warn("isDocumentWritten() called for unopened archive.");
186 if (entries.containsKey(getDocumentJarEntry()))
192 * Add unique entry strings to internal JarEntries list.
194 * @return true if entry was unique and was added.
196 private boolean addEntry(String entry) {
198 entries=new Hashtable();
199 if (entries.containsKey(entry))
201 entries.put(entry, new Integer(entries.size()));
205 * adds named entry to newarchive or returns false.
207 * @return true if entry was unique and could be added
208 * @throws IOException if entry name was invalid or a new entry could not be made on newarchive
210 private boolean addValidEntry(String entry) throws IOException {
211 JarEntry je = new JarEntry(entry);
212 if (!addEntry(entry))
214 newarchive.putNextEntry(je);
219 * opens the new archive ready for writing. If the new archive is replacing an existing one,
220 * then the existing archive will be locked, and the new archive written to a temporary file.
221 * The new archive will be put in place once close() is called.
222 * @throws IOException
224 private void openArchive() throws IOException {
226 if (newarchive!=null) {
227 log.warn("openArchive() called multiple times.");
228 throw new IOException("Vamsas Archive '"+archive.getAbsolutePath()+"' is already open.");
230 if (archive==null && (virginArchive || original==null)) {
231 log.warn("openArchive called on uninitialised VamsasArchive object.");
232 throw new IOException("Badly initialised VamsasArchive object - no archive file specified.");
234 if (!virginArchive) {
237 // make a temporary file to write to
238 archive = File.createTempFile(original.getName(), ".new",original.getParentFile());
240 if (archive.exists())
241 log.warn("New archive file name already in use! Possible lock failure imminent?");
244 rchive = new SessionFile(archive);
246 newarchive = new JarOutputStream(new BufferedOutputStream(new java.io.FileOutputStream(archive)));
247 entries = new Hashtable();
250 * Safely initializes the VAMSAS XML document Jar Entry.
251 * @return Writer to pass to the marshalling function.
252 * @throws IOException if a document entry has already been written.
254 public PrintWriter getDocumentOutputStream() throws IOException {
255 if (newarchive==null)
257 if (!isDocumentWritten()) {
259 if (addValidEntry(getDocumentJarEntry()))
260 return new PrintWriter(new java.io.OutputStreamWriter(newarchive, "UTF-8"));
261 } catch (Exception e) {
262 log.warn("Problems opening XML document JarEntry stream",e);
265 throw new IOException("Vamsas Document output stream is already written.");
270 * Opens and returns the applicationData output stream for the appdataReference string.
271 * @param appdataReference
272 * @return Output stream to write to
273 * @throws IOException
275 public AppDataOutputStream getAppDataStream(String appdataReference) throws IOException {
276 if (newarchive==null)
278 if (addValidEntry(appdataReference)) {
279 return new AppDataOutputStream(newarchive);
285 * Stops any current write to archive, and reverts to the backup if it exists.
286 * All existing locks on the original will be released. All backup files are removed.
288 public boolean cancelArchive() {
289 if (newarchive!=null) {
293 } catch (Exception e) {};
294 if (!virginArchive) {
295 // then there is something to recover.
296 if (originalBackup!=null) {
297 // backup has been made.
298 // revert from backup and delete it (changing backup filename)
300 rchive = new SessionFile(original);
302 SessionFile bckup = new SessionFile(originalBackup);
305 rchive.updateFrom(null, bckup); // recover from backup file.
308 originalBackup.delete();
311 catch (Exception e) {
312 log.warn("Problems when trying to cancel Archive "+archive.getAbsolutePath(), e);
318 log.info("cancelArchive called before archive("+original.getAbsolutePath()+") has been opened!");
320 closeAndReset(); // tidy up and release locks.
325 * only do this if you want to destroy the current file output stream
328 private void closeAndReset() {
333 if (original!=null) {
340 if (odoclock!=null) {
341 odoclock.unlockFile();
350 private final int _TRANSFER_BUFFER=4096*4;
352 * open original archive file for exclusive (locked) reading.
353 * @throws IOException
355 private void accessOriginal() throws IOException {
356 if (original!=null && original.exists()) {
358 odoclock = new SessionFile(original);
361 odoc = new VamsasArchiveReader(original);
366 * Convenience method to copy over the referred entry from the backup to the new version.
367 * Warning messages are raised if no backup exists or the
368 * entry doesn't exist in the backed-up original.
369 * Duplicate writes return true - but a warning message will also be raised.
370 * @param AppDataReference
371 * @return true if AppDataReference now exists in the new document
372 * @throws IOException
374 public boolean transferAppDataEntry(String AppDataReference) throws IOException {
375 return transferAppDataEntry(AppDataReference, AppDataReference);
378 * Transfers an AppDataReference from old to new vamsas archive, with a name change.
379 * @see transferAppDataEntry(String AppDataReference)
380 * @param AppDataReference
381 * @param NewAppDataReference - AppDataReference in new Archive
383 * @throws IOException
385 public boolean transferAppDataEntry(String AppDataReference, String NewAppDataReference) throws IOException {
386 // TODO: Specify valid AppDataReference form in all VamsasArchive handlers
387 if (AppDataReference==null)
388 throw new IOException("null AppDataReference!");
389 if (original==null || !original.exists()) {
390 log.warn("No backup archive exists.");
393 if (entries.containsKey(NewAppDataReference)) {
394 log.warn("Attempt to write '"+NewAppDataReference+"' twice! - IGNORED");
400 java.io.InputStream adstream = odoc.getAppdataStream(AppDataReference);
402 if (adstream==null) {
403 log.warn("AppDataReference '"+AppDataReference+"' doesn't exist in backup archive.");
407 java.io.OutputStream adout = getAppDataStream(NewAppDataReference);
408 // copy over the bytes
411 byte[] buffer = new byte[_TRANSFER_BUFFER]; // conservative estimate of a sensible buffer
413 if ((written = adstream.read(buffer))>-1) {
414 adout.write(buffer, 0, written);
415 log.debug("Transferring "+written+".");
418 } while (written>-1);
419 log.debug("Sucessfully transferred AppData for '"
420 +AppDataReference+"' as '"+NewAppDataReference+"' ("+count+" bytes)");
424 * Tidies up and closes archive, removing any backups that were created.
425 * NOTE: It is up to the caller to delete the original archive backup obtained from backupFile()
426 * TODO: ensure all extant AppDataReference jar entries are transferred to new Jar
427 * TODO: provide convenient mechanism for generating new unique AppDataReferences and adding them to the document
429 public void closeArchive() throws IOException {
430 if (newarchive!=null) {
431 newarchive.closeEntry();
432 if (!isDocumentWritten())
433 log.warn("Premature closure of archive '"+archive.getAbsolutePath()+"': No document has been written.");
438 log.warn("Attempt to close archive that has not been opened for writing.");
442 * Access original archive if it exists, pass the reader to the client
443 * Note: this is NOT thread safe and a call to closeArchive() will by necessity
444 * close and invalidate the VamsasArchiveReader object.
445 * @return null if no original archive exists.
447 public VamsasArchiveReader getOriginalArchiveReader() throws IOException {
448 if (!virginArchive) {
455 * returns original document's root vamsas elements.
457 * @throws IOException
458 * @throws org.exolab.castor.xml.MarshalException
459 * @throws org.exolab.castor.xml.ValidationException
461 public object[] getOriginalRoots() throws IOException,
462 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
463 return VamsasArchive.getOriginalRoots(this);
466 * Access original document if it exists, and get VAMSAS root objects.
467 * @return vector of vamsas roots from original document
468 * @throws IOException
470 public static object[] getOriginalRoots(VamsasArchive ths) throws IOException,
471 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
472 VamsasArchiveReader oReader = ths.getOriginalArchiveReader();
475 if (oReader.isValid()) {
476 InputStreamReader vdoc = new InputStreamReader(oReader.getVamsasDocumentStream());
477 VamsasDocument doc = VamsasDocument.unmarshal(vdoc);
479 return doc.getVAMSAS();
480 // TODO ensure embedded appDatas are garbage collected to save memory
482 InputStream vxmlis = oReader.getVamsasXmlStream();
483 if (vxmlis!=null) { // Might be an old vamsas file.
484 BufferedInputStream ixml = new BufferedInputStream(oReader.getVamsasXmlStream());
485 InputStreamReader vxml = new InputStreamReader(ixml);
486 VAMSAS root[] = new VAMSAS[1];
487 root[0] = VAMSAS.unmarshal(vxml);
495 protected VorbaIdFactory vorba = null;
498 * @return Returns the current VorbaIdFactory for the archive.
500 public VorbaIdFactory getVorba() {
505 * @param vorba the VorbaIdFactory to use for accessing vamsas objects.
507 public void setVorba(VorbaIdFactory vorba) {
512 * Access and return current vamsas Document, if it exists, or create a new one
513 * (without affecting VamsasArchive object state - so is NOT THREAD SAFE)
514 * TODO: possibly modify internal state to lock low-level files
515 * (like the IClientDocument interface instance constructer would do)
516 * @see org.vamsas.simpleclient.VamsasArchive.getOriginalVamsasDocument for additional caveats
519 * @throws IOException
520 * @throws org.exolab.castor.xml.MarshalException
521 * @throws org.exolab.castor.xml.ValidationException
523 public VamsasDocument getVamsasDocument() throws IOException,
524 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
525 VamsasDocument doc = getOriginalVamsasDocument(this, getVorba());
528 // Create a new document and return it
529 doc = DocumentStuff.newVamsasDocument(new VAMSAS[] { new VAMSAS()},
530 ProvenanceStuff.newProvenance("org.vamsas.simpleclient.VamsasArchive", "Created new empty document")
531 , VersionEntries.latestVersion());
535 * Access the original vamsas document for a VamsasArchive class, and return it.
536 * Users of the VamsasArchive class should use the getVamsasDocument method to retrieve
537 * the current document - only use this one if you want the 'backup' version.
538 * TODO: catch OutOfMemoryError - they are likely to occur here.
539 * NOTE: vamsas.xml datastreams are constructed as 'ALPHA_VERSION' vamsas documents.
541 * @return null if no document exists.
542 * @throws IOException
543 * @throws org.exolab.castor.xml.MarshalException
544 * @throws org.exolab.castor.xml.ValidationException
546 public static VamsasDocument getOriginalVamsasDocument(VamsasArchive ths) throws IOException,
547 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
548 return VamsasArchive.getOriginalVamsasDocument(ths, null);
550 private VorbaIdFactory makeDefaultFactory(VorbaIdFactory vorba) {
554 vorba = IdFactory.getDummyFactory("simpleclient.VamsasArchive");
555 setVorba(vorba); // save for later use
561 * Uses VorbaXmlBinder to retrieve the VamsasDocument from the original archive referred to by ths
565 * @throws IOException
566 * @throws org.exolab.castor.xml.MarshalException
567 * @throws org.exolab.castor.xml.ValidationException
569 public static VamsasDocument getOriginalVamsasDocument(VamsasArchive ths, VorbaIdFactory vorba) throws IOException,
570 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
571 VamsasArchiveReader oReader = ths.getOriginalArchiveReader();
574 vorba = ths.makeDefaultFactory(vorba);
575 if (oReader.isValid()) {
576 InputStreamReader vdoc = new InputStreamReader(oReader.getVamsasDocumentStream());
577 Object unmarsh[] = VorbaXmlBinder.getVamsasObjects(vdoc, vorba, new VamsasDocument());
579 log.fatal("Couldn't unmarshall document!");
581 object[] vobjs = (object[]) unmarsh[0];
583 VamsasDocument doc=(VamsasDocument) vobjs[0];
587 log.debug("Found no VamsasDocument object in properly formatted Vamsas Archive.");
589 // deprecated data handler
590 InputStream vxmlis = oReader.getVamsasXmlStream();
591 if (vxmlis!=null) { // Might be an old vamsas file.
592 BufferedInputStream ixml = new BufferedInputStream(oReader.getVamsasXmlStream());
593 InputStreamReader vxml = new InputStreamReader(ixml);
594 Object unmarsh[] = VorbaXmlBinder.getVamsasObjects(vxml, vorba, new VAMSAS());
597 log.fatal("Couldn't unmarshall document!");
599 VAMSAS root[]= new VAMSAS[] { null};
600 root[0] = (VAMSAS) unmarsh[0];
603 log.debug("Found no VAMSAS object in VamsasXML stream.");
605 log.debug("Making new VamsasDocument from VamsasXML stream.");
606 VamsasDocument doc = DocumentStuff.newVamsasDocument(root,
607 ProvenanceStuff.newProvenance(
608 "org.vamsas.simpleclient.VamsasArchive", // TODO: VAMSAS: decide on 'system' operations provenance form
609 "Vamsas Document constructed from vamsas.xml in <file>"
610 // TODO: VAMSAS: decide on machine readable info embedding in provenance should be done
611 +ths.original+"</file>"), VersionEntries.ALPHA_VERSION);
619 // otherwise - there was no valid original document to read.
622 public void putVamsasDocument(VamsasDocument doc) throws IOException,
623 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
624 VorbaIdFactory vorba = makeDefaultFactory(null);
625 VorbaXmlBinder.putVamsasDocument(getDocumentOutputStream(), vorba, doc);