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.VAMSAS;
19 import org.vamsas.objects.core.VamsasDocument;
22 * Class for creating a vamsas archive
24 * Writes to a temporary file and then swaps new file for backup.
25 * uses the sessionFile locking mechanism for safe I/O
29 public class VamsasArchive {
30 private static Log log = LogFactory.getLog(VamsasArchive.class);
32 * destination of new archive data
34 java.io.File archive=null;
36 * locked IO handler for new archive file
38 SessionFile rchive=null;
40 * original archive file that is to be updated
42 java.io.File original=null;
44 * original archive IO handler
46 SessionFile odoclock = null;
48 * Original archive reader class
50 VamsasArchiveReader odoc = null;
52 * true if a real vamsas document is being written.
54 boolean vamsasdocument=true;
56 * Output stream for archived data
58 JarOutputStream newarchive=null;
60 * JarEntries written to archive
62 Hashtable entries = null;
64 * true if we aren't just updating an archive
66 private boolean virginArchive=false;
68 * Create a new vamsas archive
69 * nb. No file locks are made until open() is called.
70 * @param archive - file spec for new vamsas archive
71 * @param vamsasdocument true if archive is to be a fully fledged vamsas document archive
73 public VamsasArchive(File archive, boolean vamsasdocument) {
75 if (archive==null || (archive!=null && archive.canWrite())) {
76 log.fatal("Invalid parameters for VamsasArchive constructor:"+((archive!=null)
77 ? "File cannot be overwritten." : "Null Object not valid constructor parameter"));
79 this.vamsasdocument = vamsasdocument;
80 if (archive.exists()) {
81 this.original = archive;
82 this.archive = null; // archive will be a temp file when the open method is called
86 this.archive = archive; // archive is written in place.
91 * name of backup of existing archive that has been updated/overwritten.
93 File originalBackup = null;
95 private void makeBackup() {
97 if (originalBackup==null && original!=null && original.exists()) {
100 originalBackup = odoclock.backupSessionFile(null, original.getName(), ".bak", original.getParentFile());
102 catch (IOException e) {
103 log.warn("Problem whilst making a backup of original archive.",e);
109 * called after archive is written to put file in its final place
110 * TODO: FINISH original should have sessionFile, and archive should also have sessionFile
112 private void updateOriginal() {
113 if (original!=null) {
114 if (!virginArchive) {
119 if (!archive.getAbsolutePath().equals(original)) {
120 if (originalBackup==null)
123 odoclock.updateFrom(null, rchive);
125 catch (IOException e) {
126 log.error("Problem updating archive from temporary file!",e);
129 log.warn("archive and original are the same file! ("+archive.getAbsolutePath()+")");
131 } // else virginArchive are put in correct place from the beginning
136 * called by app to get name of backup if it was made.
137 * @return null or a valid file object
139 public File backupFile() {
141 if (!virginArchive) {
143 return ((original==null) ? originalBackup : null);
149 protected String getDocumentJarEntry() {
151 return VamsasArchiveReader.VAMSASDOC;
152 return VamsasArchiveReader.VAMSASXML;
156 * @return true if Vamsas Document has been written to archive
158 protected boolean isDocumentWritten() {
159 if (newarchive==null)
160 log.warn("isDocumentWritten called for unopened archive.");
162 if (entries.containsKey(getDocumentJarEntry()))
168 * Add unique entry strings to internal JarEntries list.
170 * @return true if entry was unique and was added.
172 private boolean addEntry(String entry) {
174 entries=new Hashtable();
175 if (entries.containsKey(entry))
177 entries.put(entry, new Integer(entries.size()));
181 * adds named entry to newarchive or returns false.
183 * @return true if entry was unique and could be added
184 * @throws IOException if entry name was invalid or a new entry could not be made on newarchive
186 private boolean addValidEntry(String entry) throws IOException {
187 JarEntry je = new JarEntry(entry);
188 if (!addEntry(entry))
190 newarchive.putNextEntry(je);
195 * opens the new archive ready for writing. If the new archive is replacing an existing one,
196 * then the existing archive will be locked, and the new archive written to a temporary file.
197 * The new archive will be put in place once close() is called.
198 * @throws IOException
200 private void openArchive() throws IOException {
202 if (newarchive!=null) {
203 log.warn("openArchive() called multiple times.");
204 throw new IOException("Vamsas Archive '"+archive.getAbsolutePath()+"' is already open.");
208 if (original==null) {
209 log.warn("openArchive called on uninitialised VamsasArchive object.");
210 throw new IOException("Badly initialised VamsasArchive object - no archive file specified.");
214 // make a temporary file to write to
215 archive = File.createTempFile(original.getName(), "new",original.getParentFile());
218 rchive = new SessionFile(archive);
220 newarchive = new JarOutputStream(new BufferedOutputStream(new java.io.FileOutputStream(archive)));
221 entries = new Hashtable();
224 * Safely initializes the VAMSAS XML document Jar Entry.
225 * @return Writer to pass to the marshalling function.
226 * @throws IOException if a document entry has already been written.
228 public PrintWriter getDocumentOutputStream() throws IOException {
229 if (newarchive==null)
231 if (!isDocumentWritten()) {
233 if (addValidEntry(getDocumentJarEntry()))
234 return new PrintWriter(new java.io.OutputStreamWriter(newarchive, "UTF-8"));
235 } catch (Exception e) {
236 log.warn("Problems opening XML document JarEntry stream",e);
239 throw new IOException("Vamsas Document output stream is already written.");
244 * Opens and returns the applicationData output stream for the appdataReference string.
245 * @param appdataReference
246 * @return Output stream to write to
247 * @throws IOException
249 public AppDataOutputStream getAppDataStream(String appdataReference) throws IOException {
250 if (newarchive!=null)
252 if (addValidEntry(appdataReference)) {
253 return new AppDataOutputStream(newarchive);
259 * Stops any current write to archive, and reverts to the backup if it exists.
260 * All existing locks on the original will be released.
262 public boolean cancelArchive() {
263 if (newarchive!=null) {
266 } catch (Exception e) {};
267 if (!virginArchive) {
268 // then there is something to recover.
269 if (originalBackup!=null) {
270 // backup has been made.
271 // revert from backup and delete it (changing backup filename)
273 rchive = new SessionFile(original);
275 SessionFile bckup = new SessionFile(originalBackup);
278 rchive.updateFrom(null,bckup); // recover from backup file.
281 originalBackup.delete();
283 catch (Exception e) {
284 log.warn("Problems when trying to cancel Archive "+archive.getAbsolutePath(), e);
288 // original is untouched
289 // just delete temp files
293 log.info("cancelArchive called before archive("+original.getAbsolutePath()+") has been opened!");
300 * only do this if you want to destroy the current file output stream
303 private void closeAndReset() {
306 if (original!=null) {
312 if (odoclock!=null) {
313 odoclock.unlockFile();
322 private final int _TRANSFER_BUFFER=4096*4;
324 * open backup for exclusive (locked) reading.
325 * @throws IOException
327 private void accessOriginal() throws IOException {
328 if (original!=null && original.exists()) {
330 odoclock = new SessionFile(original);
333 odoc = new VamsasArchiveReader(original);
338 * Convenience method to copy over the referred entry from the backup to the new version.
339 * Warning messages are raised if no backup exists or the
340 * entry doesn't exist in the backed-up original.
341 * Duplicate writes return true - but a warning message will also be raised.
342 * @param AppDataReference
343 * @return true if AppDataReference now exists in the new document
344 * @throws IOException
346 public boolean transferAppDataEntry(String AppDataReference) throws IOException {
347 return transferAppDataEntry(AppDataReference, AppDataReference);
350 * Transfers an AppDataReference from old to new vamsas archive, with a name change.
351 * @see transferAppDataEntry(String AppDataReference)
352 * @param AppDataReference
353 * @param NewAppDataReference - AppDataReference in new Archive
355 * @throws IOException
357 public boolean transferAppDataEntry(String AppDataReference, String NewAppDataReference) throws IOException {
358 // TODO: Specify valid AppDataReference form in all VamsasArchive handlers
359 if (AppDataReference==null)
360 throw new IOException("null AppDataReference!");
361 if (original==null || !original.exists()) {
362 log.warn("No backup archive exists.");
365 if (entries.containsKey(NewAppDataReference)) {
366 log.warn("Attempt to write '"+NewAppDataReference+"' twice! - IGNORED");
372 java.io.InputStream adstream = odoc.getAppdataStream(AppDataReference);
374 if (adstream==null) {
375 log.warn("AppDataReference '"+AppDataReference+"' doesn't exist in backup archive.");
379 java.io.OutputStream adout = getAppDataStream(NewAppDataReference);
380 // copy over the bytes
383 byte[] buffer = new byte[_TRANSFER_BUFFER]; // conservative estimate of a sensible buffer
385 if ((written = adstream.read(buffer))>-1) {
386 adout.write(buffer, 0, written);
387 log.debug("Transferring "+written+".");
390 } while (written>-1);
391 log.debug("Sucessfully transferred AppData for '"
392 +AppDataReference+"' as '"+NewAppDataReference+"' ("+count+" bytes)");
396 * Tidies up and closes archive, removing any backups that were created.
397 * NOTE: It is up to the caller to delete the original archive backup obtained from backupFile()
399 public void closeArchive() throws IOException {
400 if (newarchive!=null) {
401 newarchive.closeEntry();
402 if (!isDocumentWritten())
403 log.warn("Premature closure of archive '"+archive.getAbsolutePath()+"': No document has been written.");
408 log.warn("Attempt to close archive that has not been opened for writing.");
412 * Access original archive if it exists, pass the reader to the client
413 * Note: this is NOT thread safe and a call to closeArchive() will by necessity
414 * close and invalidate the VamsasArchiveReader object.
415 * @return null if no original archive exists.
417 public VamsasArchiveReader getOriginalArchiveReader() throws IOException {
418 if (!virginArchive) {
426 * Access original document if it exists, and get VAMSAS root objects.
427 * @return vector of vamsas roots from original document
428 * @throws IOException
430 public static object[] getOriginalRoots(VamsasArchive ths) throws IOException,
431 org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException {
432 VamsasArchiveReader oReader = ths.getOriginalArchiveReader();
435 if (oReader.isValid()) {
436 InputStreamReader vdoc = new InputStreamReader(oReader.getVamsasDocumentStream());
437 VamsasDocument doc = VamsasDocument.unmarshal(vdoc);
439 return doc.getVAMSAS();
442 InputStream vxmlis = oReader.getVamsasXmlStream();
443 if (vxmlis!=null) { // Might be an old vamsas file.
444 BufferedInputStream ixml = new BufferedInputStream(oReader.getVamsasXmlStream());
445 InputStreamReader vxml = new InputStreamReader(ixml);
446 VAMSAS root[] = new VAMSAS[1];
447 root[0] = VAMSAS.unmarshal(vxml);