001package edu.pdx.cs410J.di;
002
003import jakarta.xml.bind.JAXBContext;
004import jakarta.xml.bind.JAXBException;
005import jakarta.xml.bind.Marshaller;
006import jakarta.xml.bind.Unmarshaller;
007
008import java.io.File;
009import java.io.IOException;
010
011/**
012 * The superclass of classes that store objects serialized to a file using JAXB
013 */
014public abstract class JaxbDatabase
015{
016    private final File directory;
017    private final String fileName;
018    private final JAXBContext xmlContext;
019    private final File file;
020
021    protected JaxbDatabase( File directory, String fileName, Class<?>... jaxbClasses )
022        throws IOException, JAXBException
023    {
024        this.directory = directory;
025        this.fileName = fileName;
026        this.xmlContext = JAXBContext.newInstance( jaxbClasses );
027
028        this.directory.mkdirs();
029        if (!this.directory.exists()) {
030          throw new IOException( "Could not create data directory: " + this.directory);
031        }
032
033
034        this.file = new File(this.directory, this.fileName);
035    }
036
037    /**
038     * Writes an object as XML to the data file
039     * @param xml The object to marshal
040     */
041    protected void writeXml( Object xml )
042    {
043        try
044        {
045            Marshaller marshaller = this.xmlContext.createMarshaller();
046            marshaller.marshal( xml, new File(this.directory, this.fileName) );
047        }
048        catch ( JAXBException ex )
049        {
050            throw new IllegalStateException( "Could not save inventory", ex);
051        }
052    }
053
054    public File getDatabaseFile() {
055        return file;
056    }
057
058    /**
059     * Read the XML data file and returns the unmarshalled object
060     * @return The object in the XML file or null if the file doesn't exist
061     * @throws JAXBException if we can't read the file
062     */
063    protected Object readFile()
064        throws JAXBException
065    {
066        System.out.println("Reading xml data from " + file );
067
068        if ( this.file.exists()) {
069          Unmarshaller unmarshaller = this.xmlContext.createUnmarshaller();
070          return unmarshaller.unmarshal( this.file );
071        } else {
072          return null;
073        }
074    }
075}