/*
 * Created on 08.01.2004 18:38:06
 *
 * Multimediale Algorithmen und Datenstrukturen Assessments
 */
package mauda;

import java.util.*;
import java.io.*;
import java.beans.*;
/**
 * Allows access to java-generated XML-files.
 * 
 * @author Markus Krebs
 */
public class XMLFileAccess {
	
	/**
	 * Loads an xml-file. All contained objects of the file will be
	 * returned in a Vector. Comment: When the file contains only
	 * one object, it must be read from the Vector via
	 * <code>Vector.firstElement()</code> 
	 * @param filename The filename of the xml-file
	 * @return Returns a Vector containing the objects of the file or null if an error occured
	 */
	public static Vector load(String filename) {
		//System.out.println("loading xml-file: "+filename);
		Vector v = new Vector();
		XMLDecoder decoder = null;
		try {
			decoder = new XMLDecoder(
										new BufferedInputStream(
										new FileInputStream(filename)));
		} catch(FileNotFoundException ex) {
			System.out.println("  -> Exception: file not found: "+filename);
			return null;
		}
		try {
			Object o = decoder.readObject();
			v.add(o);
		} catch(ArrayIndexOutOfBoundsException ex) {
			decoder.close();
		}
		return v;		
	}
	/**
	 * Saves an xml-file. All objects of the delivered vector will
	 * be saved. Comment: If only one object should be saved, a
	 * new Vector must be created, who contains this object.
	 * @param filename The filename of the xml-file
	 * @param v The Vector to save into the file
	 * @return Returns true if the saving was ok, false otherwise
	 */
	public static boolean save(String filename, Vector v) {
		XMLEncoder encoder = null;
		try {
			encoder = new XMLEncoder(
										new BufferedOutputStream(
										new FileOutputStream(filename)));
			Enumeration en = v.elements();
			while(en.hasMoreElements())
				encoder.writeObject(en.nextElement());
			encoder.close();
		} catch(FileNotFoundException ex) {
			System.out.println("  -> Exception: file not found");
			return false;
		}
		return true;
	}
}
