Skip to main content
summaryrefslogtreecommitdiffstats
blob: f0aa3ff82c1cffa8ef69577857b81e034a1683b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
/*******************************************************************************
 * Copyright (c) 2004 - 2005 University Of British Columbia and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University Of British Columbia - initial API and implementation
 *******************************************************************************/
/*
 * Created on Jan 17, 2005
 */
package org.eclipse.mylar.tasks.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.tasks.BugzillaTask;
import org.eclipse.mylar.tasks.ITask;
import org.eclipse.mylar.tasks.Task;
import org.eclipse.mylar.tasks.TaskList;
import org.eclipse.mylar.tasks.BugzillaTask.BugTaskState;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
 * @author Ken Sueda
 */
public class XmlUtil {
	
	private static String readVersion = "";

	/**
	 * 
	 * @param tlist
	 * @param outFile
	 */
	public static void writeTaskList(TaskList tlist, File outFile) {
    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db;
		Document doc = null;

		try {
			db = dbf.newDocumentBuilder();
			doc = db.newDocument();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		Element root = doc.createElement("TaskList");
		root.setAttribute("Version", "1.0.0");

		// iterate through each subtask and externalize those
		//
		for (int i = 0; i < tlist.getRootTasks().size(); i++) {
			writeTask(tlist.getRootTasks().get(i), doc, root);
		}
		doc.appendChild(root);
		writeDOMtoFile(doc, outFile);
		return;
	}
	
	/**
	 * Writes an XML file from a DOM.
	 * 
	 * doc  - the document to write
	 * file - the file to be written to
	 */
	public static void writeDOMtoFile(Document doc, File file) {
		try {
			// A file output stream is an output stream for writing data to a File
			//
			OutputStream outputStream = new FileOutputStream(file);
			writeDOMtoStream(doc, outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (Exception fnfe) {
			MylarPlugin.log(fnfe, "Tasklist could not be found");
		}
	}

	/**
	 * Writes the provided XML document out to the specified output stream.
	 * 
	 * doc - the document to be written
	 * outputStream - the stream to which the document is to be written
	 */
	public static void writeDOMtoStream(Document doc, OutputStream outputStream) {
		// Prepare the DOM document for writing
		// DOMSource - Acts as a holder for a transformation Source tree in the 
		// form of a Document Object Model (DOM) tree
		//
		Source source = new DOMSource(doc);

		// StreamResult - Acts as an holder for a XML transformation result
		// Prepare the output stream
		//
		Result result = new StreamResult(outputStream);

		// An instance of this class can be obtained with the 
		// TransformerFactory.newTransformer  method. This instance may 
		// then be used to process XML from a variety of sources and write 
		// the transformation output to a variety of sinks
		//

		Transformer xformer = null;
		try {
			xformer = TransformerFactory.newInstance().newTransformer();
			//Transform the XML Source to a Result
			//
			xformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerFactoryConfigurationError e) {
			e.printStackTrace();
		} catch (TransformerException e1) {
			e1.printStackTrace();
		}
	}

	/**
	 * 
	 * @param t
	 * @param doc
	 * @param root
	 */
	public static void writeTask(ITask t, Document doc, Element root) {

		// create node and set attributes
		//    	
		Element node = doc.createElement("Task");
		node.setAttribute("Path", t.getPath());
		node.setAttribute("Label", t.getLabel());
		node.setAttribute("Handle", t.getHandle());
		node.setAttribute("Priority", t.getPriority());

		if (t.isCategory()) {
			node.setAttribute("IsCategory", "true");
		} else {
			node.setAttribute("IsCategory", "false");
		}
		if (t.isCompleted()) {
			node.setAttribute("Complete", "true");
		} else {
			node.setAttribute("Complete", "false");
		}
		if (t.isActive()) {
			node.setAttribute("Active", "true");
		} else {
			node.setAttribute("Active", "false");
		}
		if (t instanceof BugzillaTask) {
			BugzillaTask bt = (BugzillaTask) t;
			node.setAttribute("Bugzilla", "true");
			node.setAttribute("LastDate", new Long(bt.getLastRefreshTime()
					.getTime()).toString());
			if (bt.isDirty()) {
				node.setAttribute("Dirty", "true");
			} else {
				node.setAttribute("Dirty", "false");
			}
			bt.saveBugReport(false);
		} else {
			node.setAttribute("Bugzilla", "false");
		}
		node.setAttribute("Notes", t.getNotes());
		node.setAttribute("Elapsed", t.getElapsedTime());
		node.setAttribute("Estimated", t.getEstimatedTime());
		List<String> rl = t.getRelatedLinks().getLinks();
		int i = 0;
		for (String link : rl) {
			node.setAttribute("link"+i, link);
			i++;
		}
		
		List<ITask> children = t.getChildren();

		i = 0; 
		for (i = 0; i < children.size(); i++) {
			writeTask(children.get(i), doc, node);
		}

		// append new node to root node
		//
		root.appendChild(node);
		return;
	}

	public static void readTaskList(TaskList tlist, File inFile) {
		try {
			// parse file
			//
			Document doc = openAsDOM(inFile);

			// read root node to get version number
			//
			Element root = doc.getDocumentElement();
			readVersion = root.getAttribute("Version");

			NodeList list = root.getChildNodes();
			for (int i = 0; i < list.getLength(); i++) {
				Node child = list.item(i);
				tlist.addRootTask(readTask(child, null, tlist));
			}
		} catch (Exception e) {
			String name = inFile.getAbsolutePath();
			name = name.substring(0, name.lastIndexOf('.')) + "-save.xml";
			inFile.renameTo(new File(name));
			MylarPlugin.log(e, "XmlUtil");
		}
	}

	/**
	 * Opens the specified XML file and parses it into a DOM Document.
	 * 
	 * Filename - the name of the file to open
	 * Return   - the Document built from the XML file
	 * Throws   - XMLException if the file cannot be parsed as XML
	 *          - IOException if the file cannot be opened
	 */
	public static Document openAsDOM(File inputFile) throws IOException {

		// A factory API that enables applications to obtain a parser 
		// that produces DOM object trees from XML documents
		//
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		// Using DocumentBuilder, obtain a Document from XML file.
		//
		DocumentBuilder builder = null;
		Document document = null;
		try {
			// create new instance of DocumentBuilder
			//
			builder = factory.newDocumentBuilder();
		} catch (ParserConfigurationException pce) {
			inputFile.renameTo(new File(inputFile.getName() + "save.xml"));
			MylarPlugin.log(pce, "Failed to load XML file");
		}
		try {
			// Parse the content of the given file as an XML document 
			// and return a new DOM Document object. Also throws IOException
			document = builder.parse(inputFile);
		} catch (SAXException se) {
			inputFile.renameTo(new File(inputFile.getName() + "save.xml"));
			MylarPlugin.log(se, "Failed to parse XML file");
		}
		return document;
	}
	
	public static ITask readTask(Node node, ITask root, TaskList tlist) {
		//extract node and create new sub task
		//
		Element e = (Element) node;
		ITask t;
		String handle = "";
		if (e.hasAttribute("ID")) {
			handle = e.getAttribute("ID");
		} else {
			handle = e.getAttribute("Handle");
		}
		
		String label = e.getAttribute("Label");
		String priority = e.getAttribute("Priority");

		if (e.getAttribute("Bugzilla").compareTo("true") == 0) {
			t = new BugzillaTask(handle, label, true);
			BugzillaTask bt = (BugzillaTask) t;
			bt.setState(BugTaskState.FREE);
			bt.setLastRefresh(new Date(new Long(e.getAttribute("LastDate"))
					.longValue()));
			if (e.getAttribute("Dirty").compareTo("true") == 0) {
				bt.setDirty(true);
			} else {
				bt.setDirty(false);
			}
			if (bt.readBugReport() == false) {
				MylarPlugin.log("Failed to read bug report", null);
			}
		} else {
			t = new Task(handle, label);			
		}
		t.setPriority(priority);
		t.setPath(e.getAttribute("Path"));
		
		if (e.getAttribute("Active").compareTo("true") == 0) {
			t.setActive(true);
			tlist.setActive(t, true);
		} else {
			t.setActive(false);
		}

		if (e.getAttribute("Complete").compareTo("true") == 0) {
			t.setCompleted(true);
		} else {
			t.setCompleted(false);
		}
		if (e.getAttribute("IsCategory").compareTo("true") == 0) {
			t.setIsCategory(true);
		} else {
			t.setIsCategory(false);
		}

		if (e.hasAttribute("Notes")) {
			t.setNotes(e.getAttribute("Notes"));			
		} else {
			t.setNotes("");
		}
		if (e.hasAttribute("Elapsed")) {
			t.setElapsedTime(e.getAttribute("Elapsed"));			
		} else {
			t.setElapsedTime("");
		}
		if (e.hasAttribute("Estimated")) {
			t.setEstimatedTime(e.getAttribute("Estimated"));			
		} else {
			t.setEstimatedTime("");
		}
		
		int i = 0;
		while (e.hasAttribute("link"+i)) {
			t.getRelatedLinks().add(e.getAttribute("link"+i));
			i++;
		}
				
		if (!readVersion.equals("1.0.0")) {
			// for newer revisions
			// XXX: readVersion had to be read once to remove warning..
		}

		i = 0;
		NodeList list = e.getChildNodes();
		for (i = 0; i < list.getLength(); i++) {
			Node child = list.item(i);
			t.addSubtask(readTask(child, t, tlist));
		}
		if (root != null) {
			t.setParent(root);
		}
		return t;
	}	
}

Back to the top