View Javadoc

1   package at.ac.tuwien.ifs.bpse.basic.export_import;
2   
3   import java.io.FileInputStream;
4   import java.io.FileOutputStream;
5   import java.io.IOException;
6   import java.io.InputStream;
7   import java.util.ArrayList;
8   import java.util.List;
9   
10  import org.apache.commons.logging.Log;
11  import org.apache.commons.logging.LogFactory;
12  import org.dom4j.Document;
13  import org.dom4j.DocumentException;
14  import org.dom4j.DocumentFactory;
15  import org.dom4j.Element;
16  import org.dom4j.io.OutputFormat;
17  import org.dom4j.io.SAXReader;
18  import org.dom4j.io.XMLWriter;
19  
20  import at.ac.tuwien.ifs.bpse.basic.domain.Student;
21  
22  
23  /**
24   * This class can be used for importing and exporting xml-files. It uses dom4j
25   * to generate/read an XML-file. This is much more flexible than using simple
26   * Sting concationation (as used in the {@link HtmlExport}-Class. More
27   * informaton about dom4j is available on the dom4j-website.
28   * 
29   * @author The SE-Team
30   * @version 1.0
31   * @see Export
32   * @see Import
33   * @see <a href="http://dom4j.org" target="newWindow">dom4j-website</a>
34   */
35  public class XmlExportImport implements Export, Import {
36  
37  	/**
38  	 * Retrieves the logger for this class.
39  	 */
40  	private static Log log = LogFactory.getLog(XmlExportImport.class);
41  
42  	/**
43  	 * The Document Factory instance is retrieved once.
44  	 */
45  	private DocumentFactory documentFactory = DocumentFactory.getInstance();
46  
47  	/**
48  	 * The Document to Export/Import.
49  	 */
50  	private Document doc = null;
51  
52  	/**
53  	 * Default encoding in which to input/ouput text.
54  	 */
55  	private String encoding = "utf-8";
56  
57  	/**
58  	 * Creates a new Instance. Nothing special here.
59  	 * 
60  	 */
61  	public XmlExportImport() {
62  		super();
63  	}
64  
65  	/**
66  	 * Used for display purposes in the UI models. Very important as it is
67  	 * implemented to stringify this object.
68  	 * 
69  	 * @return String "XML" for this export
70  	 * 
71  	 */
72  	public String toString() {
73  		return "XML";
74  	}
75  
76  	/**
77  	 * This method is required to give the GUI components Feedback which File
78  	 * extension this Export Type usually creates.
79  	 */
80  	public String getExtension() {
81  		return "xml";
82  	}
83  
84  	/**
85  	 * Returns the encoding of the XML-File. eg. "utf-8"
86  	 * 
87  	 * @return the encoding of the xml-file.
88  	 */
89  	public String getEncoding() {
90  		return encoding;
91  	}
92  
93  	/**
94  	 * Sets the encoding of the xml-file. Xml-files can be created using
95  	 * different character-encodings. The most common and widely used encoding
96  	 * is "utf-8", which is the default value.
97  	 * 
98  	 * @param encoding
99  	 *            the encoding if the xml-file.
100 	 */
101 	public void setEncoding(String encoding) {
102 		this.encoding = encoding;
103 	}
104 
105 	/**
106 	 * Returns the Xml-Document.
107 	 * 
108 	 * @return the XML-Document.
109 	 */
110 	public Document getDocument() {
111 		return doc;
112 	}
113 
114 	/**
115 	 * Generates Root Element of XML Document.
116 	 * 
117 	 * @return root Element
118 	 */
119 	private Element generateRoot() {
120 		log.debug("Generate Root Element");
121 		doc = documentFactory.createDocument();
122 		Element root = doc.addElement("students");
123 		return root;
124 	}
125 
126 	/**
127 	 * Generate XML Dom Tree in Memory from Studenten-Objects.
128 	 * 
129 	 * @param studenten
130 	 *            List of Student Objects
131 	 */
132 	public void generateXML(List<Student> studenten) {
133 		log.info("Start Generating XML");
134 		Element rootEl = generateRoot();
135 
136 		for (Student s : studenten) {
137 			// generate Elements
138 			log.debug("Generate <student> Element:");
139 			Element studentEl = rootEl.addElement("student");
140 			Element vornameEl = studentEl.addElement("firstname");
141 			Element nachnameEl = studentEl.addElement("lastname");
142 			Element matnrEl = studentEl.addElement("matnr");
143 			Element emailEl = studentEl.addElement("email");
144 			// set Element Content
145 			vornameEl.setText(s.getFirstname());
146 			nachnameEl.setText(s.getLastname());
147 			matnrEl.setText(s.getMatnr());
148 			emailEl.setText(s.getEmail());
149 			// Set ID as attribute
150 			String id = s.getId() + "";
151 			studentEl.addAttribute("id", id);
152 			log.debug("(" + id + ") " + s.getFirstname() + " " + s.getLastname()
153 					+ " " + s.getMatnr() + " " + s.getEmail());
154 		}
155 		log.info("Finished Generating XML");
156 	}
157 
158 	/**
159 	 * Saves the XML-Document to a file.
160 	 * 
161 	 * @param filename
162 	 *            the filename.
163 	 * @throws IOException
164 	 *             on errors while writing the file.
165 	 */
166 	public void save(String filename) throws IOException {
167 		log.info("Saving XML Data to file \"" + filename + "\"");
168 		FileOutputStream fos = new FileOutputStream(filename);
169 		OutputFormat outForm = OutputFormat.createPrettyPrint();
170 		outForm.setEncoding(encoding);
171 		XMLWriter xwriter = new XMLWriter(fos, outForm);
172 		xwriter.write(doc);
173 	}
174 
175 	/**
176 	 * Reads the XML-Document from a file on the filesystem.
177 	 * 
178 	 * @param filename
179 	 *            The file to read.
180 	 * @throws DocumentException
181 	 *             on errors while reading.
182 	 */
183 	public void readXml(String filename) throws DocumentException, IOException {
184 		log.info("Reading XML Data from file \"" + filename + "\"");
185 		SAXReader xmlReader = new SAXReader();
186 		InputStream is = new FileInputStream(filename);
187 		doc = xmlReader.read(is);
188 		is.close();
189 	}
190 
191 	/**
192 	 * Writes the given Students to the given file. This mehtod just calls other
193 	 * (private) methods of this class.
194 	 * 
195 	 * @see #generateXML(List)
196 	 * @see #save(String)
197 	 */
198 	public void write(List<Student> studenten, String filename)
199 			throws IOException {
200 		generateXML(studenten);
201 		save(filename);
202 	}
203 
204 	/**
205 	 * This method reads a List of Students from a xml-file. It uses a
206 	 * dom4j-Document which provides easy to use methods for accessing the
207 	 * elements of the XML-Tree.
208 	 * 
209 	 * @param filename The file to read.
210 	 * @return list of students
211 	 * @see #readXml(String)
212 	 */
213 	@SuppressWarnings("unchecked")
214 	public List<Student> read(String filename) throws IOException {
215 		try {
216 			readXml(filename);
217 		} catch (DocumentException e) {
218 			log.error("" + e);
219 			throw new IOException("" + e);
220 		}
221 		List<Student> studenten = new ArrayList<Student>();
222 		List<Element> studentenEl = (List<Element>) doc.getRootElement().elements();
223 		for (Element e: studentenEl) {
224 			Student s = new Student();
225 			s.setId(new Integer(e.attributeValue("id")));
226 			s.setFirstname(e.elementText("firstname"));
227 			s.setLastname(e.elementText("lastname"));
228 			s.setEmail(e.elementText("email"));
229 			s.setMatnr(e.elementText("matnr"));
230 			studenten.add(s);
231 		}
232 		return studenten;
233 	}
234 
235 }